如何修改文本文件?

2024-04-20 10:02:01 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

如果使用inplace=1参数,Python标准库的^{}模块将重写文件inplace:

import sys
import fileinput

# replace all occurrences of 'sit' with 'SIT' and insert a line after the 5th
for i, line in enumerate(fileinput.input('lorem_ipsum.txt', inplace=1)):
    sys.stdout.write(line.replace('sit', 'SIT'))  # replace 'sit' and write
    if i == 4: sys.stdout.write('\n')  # write a blank line after the 5th line

不幸的是,如果不重新写入文件,就无法将其插入文件的中间。如前几张海报所示,可以使用seek将其附加到文件或覆盖其中的一部分,但如果要在文件的开头或中间添加内容,则必须重写它。

这是操作系统的事情,不是Python的事情。所有语言都是一样的。

我通常做的是从文件中读取,进行修改并将其写入一个名为myfile.txt.tmp的新文件或类似的文件。这比将整个文件读入内存要好,因为文件可能太大。临时文件完成后,我将其重命名为与原始文件相同的名称。

这是一个很好的、安全的方法,因为如果文件写操作由于任何原因崩溃或中止,您仍然有未触及的原始文件。

取决于你想做什么。要附加,可以用“a”打开它:

 with open("foo.txt", "a") as f:
     f.write("new line\n")

如果要预打印,必须先从文件中读取:

with open("foo.txt", "r+") as f:
     old = f.read() # read everything in the file
     f.seek(0) # rewind
     f.write("new line\n" + old) # write the new line before

相关问题 更多 >