如何在文件中插入行

时间:2014-11-12 10:53:37

标签: python string writefile

我想在文件中插入一行。如下所示,一旦'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

有一些问题,但没有得到妥善回答。我真的很想知道下来的人,你有什么问题吗?或者你无法理解?或者只是因为一些不会影响问题的小错误?

3 个答案:

答案 0 :(得分:0)

更新文件inplace use fileinput module,

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

答案 1 :(得分: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))

答案 2 :(得分: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)