有时,当我在Python中打开文件进行读取或写入时
f = open('workfile', 'r')或
f = open('workfile', 'w')我读/写该文件,然后在最后忘记执行f.close()。有没有办法在所有读/写操作完成后,或者在代码完成处理后自动关闭?
发布于 2014-02-13 10:12:02
无论你对你的文件做了什么,在你读入它之后,你应该这样读写它:
$ python myscript.py sample.txt sample1.txt
那么第一个参数(sample.txt)就是我们的“旧文件”,第二个参数(sample1.txt)就是我们的“新文件”。然后,您可以在名为"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()https://stackoverflow.com/questions/16503378
复制相似问题