如何使用Python程序打开文件并对其执行某些操作?

时间:2018-01-04 07:33:20

标签: python-3.x file

如何在python程序中打开文件并让它对文件执行某些操作?

2 个答案:

答案 0 :(得分:0)

使用它 当您执行代码时,运算符将自动关闭文件

with open('your_file_name.extension', 'rw') as myfile:
        content = myfile.read()
        #do something with content
        myfile.write('some string') #add some content

答案 1 :(得分:0)

最好的方法是使用with语句。

with open('file.txt', 'w') as file:
    file.write('test')

但是有关更多信息,请按照官方文档: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files