简体   繁体   English

如何在文件中插入行

[英]how to insert line in file

I want to insert a line in a file. 我想在文件中插入一行。 like below, insert '111' once 'AAA' appears 如下所示,一旦出现“ AAA”,请插入“ 111”

original file 原始文件

AAA
BBB
CCC
AAA
DDD
AAA

and I want the result to be : 我希望结果是:

AAA
111
BBB
CCC
AAA
111
DDD
AAA
111

Here are my codes 这是我的代码

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

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

But it turns out that every time I run it, python just add '111' at the end of file, not just behind where 'AAA' starts, like below. 但是事实证明,每次我运行python时,都只在文件末尾添加“ 111”,而不是仅在“ AAA”开始的后面添加,如下所示。

AAA
BBB
CCC
AAA
DDD
AAA111

There are some questions about this, but they are not properly answered. 关于此有一些问题,但未正确回答。 I really wonder the downvoters, do you have any problems ? 我真的很想知道那些下注者,您有什么问题吗? or you cannot understand? 还是你听不懂? or just because of some small mistakes that doesn't affect the question? 还是仅仅因为一些小错误而不会影响问题?

To Update the file inplace use fileinput module, 要使用文件fileinput模块就地更新文件,

import fileinput

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

output:- 输出: -

AAA
111
BBB
CCC
AAA
111
DDD
AAA
111

r+ addds to the end of the file. r+添加到文件末尾。 This is not what you want. 这不是您想要的。 Just split your code into reading and writing: 只需将代码拆分为读写即可:

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))
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)

Output: 输出:

AAA
111
BBB
CCC
AAA
111
DDD
AAA
111

If you want to write to a new file and avoid reading all the file into memory: 如果要写入新文件并避免将所有文件读入内存,请执行以下操作:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM