【问题标题】:Should we open the file more than once to read it?我们应该多次打开文件来阅读它吗?
【发布时间】:2016-01-03 10:08:36
【问题描述】:

我有以下 Python 脚本。我注意到每次read()write() 之后我都必须open() 文件。是不是因为这样操作后文件会自动关闭?

text_file = open('Text.txt','r')
print 'The file content BEFORE writing content:'
print text_file.read()
text_file = open('Text.txt','a')
text_file.write(' add this text to the file')
print 'The file content AFTER writing content:'
text_file = open('Text.txt','r')
print text_file.read()

谢谢。

【问题讨论】:

  • 不,您不需要多次打开文件。

标签: python file io


【解决方案1】:

r+模式和seek(0)打开:

with open('Text.txt', 'r+') as text_file:
    print 'The file content BEFORE writing content:'
    print text_file.read()
    text_file.write(' add this text to the file')
    print 'The file content AFTER writing content:'
    text_file.seek(0)
    print text_file.read()

打印:

The file content BEFORE writing content:
abc
The file content AFTER writing content:
abc add this text to the file

docs有详细信息:

'+'打开一个磁盘文件进行更新(读写)

seek() 可让您在文件中移动:

更改流位置。

将流位置更改为给定的字节偏移量。偏移量是 相对于 wherece 指示的位置进行解释。价值观 因为是:

  • 0 -- 流的开始(默认);偏移量应为零或正数
  • 1 -- 当前流位置;偏移量可能为负数
  • 2 -- 流结束;偏移量通常为负数

返回新的绝对位置。

【讨论】:

    【解决方案2】:

    是不是因为这样操作后文件会自动关闭?

    没有。该文件已打开且未明确关闭。但是当您通读文件时,文件位置会转到文件末尾。

    如果以只读模式打开文件,则无法写入文件(r)。 您必须以write 模式打开文件:(w/a/r+/wb)。读取文件后,您可以使用文件对象的seek() 方法移动文件位置。

    此外,如果您使用open 函数打开文件,则必须显式关闭该文件。您可以使用:

    with open('Text.txt', 'r') as text_file:
        # your code
    

    这将在代码块执行后关闭文件。

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 2012-03-08
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 2010-12-01
      • 2017-12-16
      • 2010-09-10
      相关资源
      最近更新 更多