python - 如何逐行编辑文件并根据条件将文本插入文档?
问题描述
我有一个名为 words.txt 的文件。它是 5 行字母:
a
b
c
d
我想让 python 逐行读取这个文件。如果b
后面跟着c
,我想插入 3 个零,即0
, 0
, 0
,并将它们作为 3 行附加到b
同一文件(或不同的文件)下。所需的结果将是一个名为 words_edited.txt 的新文本文件,如下所示:
a
b
0
0
0
c
d
到目前为止,这是我的代码:
def function():
infile = open('words.txt')
outfile = open('words_edited.txt', 'w')
for line in infile:
if line == 'b' and next(infile) == 'c':
outfile.write('0\n0\n0\n')
if __name__ == '__main__':
function()
解决方案
首先,您需要实际阅读这些行,因此您需要替换infile = open('words.txt')
为
infile = open('words.txt')
letters = infile.readlines()
或者更好的是.read().splitlines()
用来去掉\n
每个字母后的尾随字符。['a', 'b', 'c', 'd']
如果您在修改后打印 infile,如果您选择后一种选项,您应该会看到如下所示的列表。现在您正在使用一个列表,您可以简单地对其进行迭代,将元素添加到另一个列表中,并检查当前字母是否为 b,是否后面跟着 c,以及是否也将零添加到列表中。完成后,您可以将列表元素加入字符串并将其写入输出文件。完成使用后不要忘记关闭文件。生成的代码如下所示:
def function():
infile = open('words.txt')
letters = infile.read().splitlines()
outfile = open('words_edited.txt', 'w')
res = []
n = len(letters)
for i in range(n):
res.append(letters[i])
if letters[i] == 'b' and i + 1 != n and letters[i+1] == 'c':
res.append('0\n0\n0')
outfile.write('\n'.join(res))
infile.close()
outfile.close()
if __name__ == '__main__':
function()
可能有一种更有效的方法来做到这一点,但我想让它尽可能简单,以便您更好地理解它。