how to insert line in file

446 views Asked by At

I want to insert a line in a file. like below, insert '111' once 'AAA' appears

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.

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?

3

There are 3 answers

3
Vishnu Upadhyay On BEST ANSWER

To Update the file 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, 

output:-

AAA
111
BBB
CCC
AAA
111
DDD
AAA
111
0
k-nut On

r+ addds to the end of the file. 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))
0
Padraic Cunningham On
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)