如何修改文本文件?
我在用Python,想要把一个字符串插入到一个文本文件里,但不想删除或复制这个文件。我该怎么做呢?
8 个回答
84
Python标准库中的fileinput
模块可以直接在文件中进行修改。如果你使用了inplace=1这个参数,它就会在原地重写文件,也就是说会直接在原文件上进行更改,而不是创建一个新的文件。
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
142
这要看你想做什么。如果你想在文件末尾添加内容,可以用“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
163
很遗憾,想要在文件中间插入内容是没办法的,必须重新写一遍整个文件。就像之前的朋友们说的,你可以在文件末尾添加内容,或者用“seek”命令覆盖文件的一部分,但如果你想在开头或中间加东西,就得重新写文件。
这其实是操作系统的限制,不是Python特有的情况。所有编程语言都是一样的。
我通常的做法是先从文件中读取内容,进行修改后再写入一个新的文件,比如叫myfile.txt.tmp之类的。这样做比把整个文件读到内存中要好,因为文件可能太大,内存装不下。一旦临时文件写完,我就把它重命名为和原文件一样的名字。
这种方法安全又可靠,因为如果在写文件的过程中出现崩溃或者中断,你的原文件还是完好无损的。