Search code examples
pythonstringwritefile

how to insert line in file


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?


Solution

  • 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