【问题标题】:How to make a file open with Python program and do something with it?如何使用 Python 程序打开文件并对其进行处理?
【发布时间】:2018-01-04 07:33:20
【问题描述】:

如何让一个文件在 python 程序中打开并让它对文件做一些事情?

【问题讨论】:

标签: python-3.x file


【解决方案1】:

使用这个 当你在其中执行代码时,with 运算符将自动关闭文件

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

【讨论】:

    【解决方案2】:

    最好的方法是使用with 声明。

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

    但要了解更多信息,请遵循官方文档: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 2010-12-31
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多