Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove and insert lines in a text file

Tags:

python

file-io

I have a text file looks like:

first line  
second line  
third line  
forth line  
fifth line  
sixth line

I want to replace the third and forth lines with three new lines. The above contents would become:

first line  
second line  
new line1  
new line2  
new line3    
fifth line  
sixth line

How can I do this using Python?

like image 724
Nimmy Avatar asked Dec 03 '22 13:12

Nimmy


1 Answers

For python2.6

with open("file1") as infile:
    with open("file2","w") as outfile:
        for i,line in enumerate(infile):
            if i==2:
                # 3rd line
                outfile.write("new line1\n")
                outfile.write("new line2\n")
                outfile.write("new line3\n")
            elif i==3:
                # 4th line
                pass
            else:
                outfile.write(line)

For python3.1

with open("file1") as infile, open("file2","w") as outfile:
    for i,line in enumerate(infile):
        if i==2:
            # 3rd line
            outfile.write("new line1\n")
            outfile.write("new line2\n")
            outfile.write("new line3\n")
        elif i==3:
            # 4th line
            pass
        else:
            outfile.write(line)
like image 133
John La Rooy Avatar answered Dec 24 '22 03:12

John La Rooy