有时当我打开一个文件以在 Python 中读取或写入时
f = open('workfile', 'r')
或者
f = open('workfile', 'w')
我读/写文件,最后我忘了做f.close()
. 有没有办法在所有读/写完成后自动关闭,或者在代码完成处理后自动关闭?
with open('file.txt','r') as f:
#file is opened and accessible via f
pass
#file will be closed before here
你总是可以使用with...as语句
with open('workfile') as f:
"""Do something with file"""
或者你也可以使用try...finally 块
f = open('workfile', 'r')
try:
"""Do something with file"""
finally:
f.close()
虽然你说你忘记添加 f.close(),但我猜 with...as 语句对你来说是最好的,而且考虑到它的简单性,很难看出不使用它的原因!
Whatever you do with your file, after you read it in, this is how you should read and write it back:
$ python myscript.py sample.txt sample1.txt
Then the first argument (sample.txt) is our "oldfile" and the second argument (sample1.txt) is our "newfile". You can then do the following code into a file called "myscript.py"
from sys import argv
script_name,oldfile,newfile = argv
content = open(oldfile,"r").read()
# now, you can rearrange your content here
t = open(newfile,"w")
t.write(content)
t.close()