0

我想在文件中插入一行。如下所示,一旦出现“AAA”,插入“111”

原始文件

AAA
BBB
CCC
AAA
DDD
AAA

我希望结果是:

AAA
111
BBB
CCC
AAA
111
DDD
AAA
111

这是我的代码

with open(outfile, 'r+') as outfile:
        for line in outfile:    

            if line.startswith('AAA'):
                outfile.write('111\n')
                outfile.flush() 

但事实证明,每次我运行它时,python 只是在文件末尾添加“111”,而不仅仅是在“AAA”开始的位置后面,如下所示。

AAA
BBB
CCC
AAA
DDD
AAA111

对此有一些问题,但没有得到适当的回答。我真的很想知道投票者,你有什么问题吗?或者你无法理解?还是仅仅因为一些不影响问题的小错误?

4

3 回答 3

1

要更新文件就地使用fileinput模块,

import fileinput

for line in fileinput.input(outfile, inplace=True):
    if line.strip() == 'AAA':
        print line,
        print 111
    else:
        print line, 

输出:-

AAA
111
BBB
CCC
AAA
111
DDD
AAA
111
于 2014-11-12T10:59:06.380 回答
0

r+添加到文件末尾。这不是你想要的。只需将您的代码分成阅读和写作:

filepath = "/file.txt"
with open(filepath, 'r') as infile:
    content = infile.readlines()

out = []
with open(filepath 'w') as outfile:
        for line in content:
            out.append(line)
            if line.startswith('A'):
                out.append("111\n")
        outfile.write("".join(out))
于 2014-11-12T11:01:11.460 回答
0
with open("in.txt") as f:
    lines = f.readlines()
    for ind, line in enumerate(lines):
        if line.rstrip() == "AAA":
            lines[ind] = line.rstrip() + "\n111\n"
    with open("in.txt","w") as f1:
        f1.writelines(lines)

输出:

AAA
111
BBB
CCC
AAA
111
DDD
AAA
111

如果要写入新文件并避免将所有文件读入内存:

with open("in.txt") as f,open("output.txt","w") as f1:
    for  line in f:
        if line.rstrip() == "AAA":
            f1.write(line.rstrip() + "\n111\n")
        else:
            f1.write(line)
于 2014-11-12T11:08:52.517 回答