当前位置: 动力学知识库 > 问答 > 编程问答 >

opening and manipulating text files with python

问题描述:

So I've done a lot of browsing, but I cant seem to open my text file so I can begin to manipulate it.

I saved my program in with the same file: and my first line returns no errors:

fpath= r'/Users/veggiepunk1363/Desktop/geoproccessing/file_list.txt'

with open(fpath) as f_in:

dates= f_in.read()

f_in.close()

But now is my file open? The text file (file_list.txt) is:

3B43.20000101.7.tif

3B43.20000201.7.tif

3B43.20000301.7.tif

3B43.20000401.7.tif

3B43.20000501.7.tif...

and so on, so now I need to assign dates(jan, feb, mar etc) instead of numbers, but I havent used anything without "" so I'm a little lost and while I can find a lot on CSV files I havent been able to find what I need on txt files so any references would be much appreciated.

Thanks!

ps. If anyone knows how to change my hard drives name to something other than veggiepunk1363 PLEASE let me know! haha

my new code:

f = open('/Users/veggiepunk1363/Desktop/geoproccessing/file_listmaster3.txt','r')

filedata = f.read()

f.close()

Jan = filedata.replace("20001","2000Jan")

Feb = filedata.replace("20002","2000Feb")

Mar= filedata.replace("20003","2000Mar")

Apr= filedata.replace("20004","2000Apr")

May= filedata.replace("20005","2000May")

Jun= filedata.replace("20006","2000Jun")

Jul= filedata.replace("20007","2000Jul")

Aug= filedata.replace("20008","2000Aug")

Sep= filedata.replace("20009","2000Sep")

Oct= filedata.replace("20010","2000Oct")

Nov= filedata.replace("20011","2000Nov")

Dec= filedata.replace("20012","2000Dec")

f = open('/Users/veggiepunk1363/Desktop/geoproccessing/file_listmaster3.txt','w')

f.write(Jan)

f.write(Feb)

f.write(Mar)

f.write(Apr)

f.write(May)

f.write(Jun)

f.write(Jul)

f.write(Aug)

f.write(Sep)

f.write(Oct)

f.write(Nov)

f.write(Dec)

print ('The dates have been reformatted')

f.close()

I know this is the long way to do what I'm trying to do, but I thought it would still work... it didnt. it tripled the size of my txt file and it looks like everything was duplicated? not quite sure what is going on.

网友答案:

You need not use a context manager. This is much simpler and does not require you to explicitly close the file descriptor:

for file_name in open(fpath).readlines():
    print file_name  # 3B43.20000101.7.tif...
网友答案:

Try this way. veggiepunk1363 is not the name of your hard drive. It is the folder in which your User files resides on Windows.

fpath= r'/Users/veggiepunk1363/Desktop/geoproccessing/file_list.txt'

with open(fpath, 'r') as f_in: #opens the file with read mode 
    dates = f_in.readlines()   #returns a list of all the lines in the file into dates
分享给朋友:
您可能感兴趣的文章:
随机阅读: