如何在python的Open文件中的某些子串之前和之后编写?

我正在试图找出如何读取文件,找到某些子串,并编辑输入的文件以在该子串之前和之后写入字符,但我卡住了.我只能弄清楚如何写入文件的末尾而不是在某个地方中间的文件中间!

例如,假设我有一个文本文件:

blah blurh blap

然后我有代码:

f = open('inputFile.txt', 'r+')
for line in f:                          
    if 'blah' in line:
        f.write('!')
f.close()

上面写的方式,结果文本会说:

blah blurh blap!

但我需要一种方法来弄清楚它:

!blah! blurh blap

我无法弄明白,也无法在网上找到任何关于它的信息.有任何想法吗?

最佳答案 如评论中所述,一种方法是写入另一个临时文件,然后重命名它.

这种方式的内存成本较低,虽然它会占用磁盘空间的2倍.

import os
with open('inputFile.txt', 'r') as inp, open('outfile.txt', 'w') as out:
    for line in inp:
        out.write(line.replace('blah', '!blah!'))
# Windows doesn't let you overwrite a file, remove it old input first
os.unlink('inputFile.txt')
os.rename('outfile.txt', 'inputFile.txt')

或者您可以将文件完全加载到内存中,然后重新编写它.

with open('inputFile.txt', 'r') as inp:
    fixed = inp.read().replace('blah', '!blah!')
with open('inputFile.txt', 'w') as out:
    out.write(fixed)
点赞