【发布时间】:2018-01-04 07:33:20
【问题描述】:
如何让一个文件在 python 程序中打开并让它对文件做一些事情?
【问题讨论】:
标签: python-3.x file
如何让一个文件在 python 程序中打开并让它对文件做一些事情?
【问题讨论】:
标签: python-3.x file
使用这个 当你在其中执行代码时,with 运算符将自动关闭文件
with open('your_file_name.extension', 'rw') as myfile:
content = myfile.read()
#do something with content
myfile.write('some string') #add some content
【讨论】:
最好的方法是使用with 声明。
with open('file.txt', 'w') as file:
file.write('test')
但要了解更多信息,请遵循官方文档: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
【讨论】: