Python 在文本文件中删除和插入行

Python 在文本文件中删除和插入行,python,file-io,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 一线 第二线 新线路1 新线路2 新线路3

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

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 一线 第二线 新线路1 新线路2 新线路3 第五行 第六行
如何使用Python完成此操作?

打开第二个文件进行写入,读取然后写入要复制的行,写入新行,读取要跳过的行,然后复制其余的行。

将整个文件作为行列表读取,然后用新的行列表替换要删除的行:

f = open('file.txt')
data = f.readlines()
f.close()
data[2:4] = [
    'new line1\n',
    'new line2\n',
    'new line3\n']
f = open('processed.txt','w')
f.writelines(data)
f.close()

请注意,列表切片是基于零的,[2:4]表示“元素2到但不包括元素4”。

有几种方法可以实现这一点

  • 如果您的文件很小,并且行是唯一的,您可以读取整个文件并替换行

    f、 read().替换(“第三行”,“新的第1行\n新的第2行\n新的第3行”)

  • 但是,如果文件很大或者没有行,只需逐行读取文件,并输出每一行,但在第三行输出三个不同的行

  • e、 g


    对于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)
    
    对于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)
    
    希望这有帮助

    import fileinput
    myinsert="""new line1\nnew line2\nnew line3"""
    for line in fileinput.input("file",inplace=1):
        linenum=fileinput.lineno()
        if linenum==1 or linenum>4 : 
            line=line.rstrip()
        if linenum==2:
            line=line+myinsert
        print line
    
    或者如果你的文件不是太大

    import os
    myinsert=["new line3\n","new line2\n","new line1\n"]
    data=open("file").readlines()
    data[2:4]=""
    for i in myinsert:data.insert(2,i)
    open("outfile","w").write(''.join(data))
    os.rename("outfile","file)
    

    这是很理想的,因为(与其他一些建议不同)它不需要将整个文件(未指定大小)读入内存。@Charles Duffy,Mark Tolonen的解决方案是我在这里看到的唯一一个在指定size时将文件读入内存的解决方案……”我有一个文本文件[看起来像::^)@gnibbler-anurag也这样做,在撰写我的评论时,排名第一的答案是一个全内存解决方案,作为两个建议解决方案中的第一个。没有必要使用可用的
    enumerate()
    维护您自己的计数器。
    import fileinput
    myinsert="""new line1\nnew line2\nnew line3"""
    for line in fileinput.input("file",inplace=1):
        linenum=fileinput.lineno()
        if linenum==1 or linenum>4 : 
            line=line.rstrip()
        if linenum==2:
            line=line+myinsert
        print line
    
    import os
    myinsert=["new line3\n","new line2\n","new line1\n"]
    data=open("file").readlines()
    data[2:4]=""
    for i in myinsert:data.insert(2,i)
    open("outfile","w").write(''.join(data))
    os.rename("outfile","file)