删除并在文本文件中插入行

Nim*_*mmy 4 python file-io

我有一个文本文件看起来像:

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

我想用三个新行替换第三行和第四行.以上内容将成为:

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

我怎么能用Python做到这一点?

Joh*_*ooy 7

对于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)
Run Code Online (Sandbox Code Playgroud)

对于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)
Run Code Online (Sandbox Code Playgroud)