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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2305115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:19:23  来源:igfitidea点击:

Remove and insert lines in a text file

pythonfile-io

提问by Nimmy

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?

我怎样才能使用 Python 做到这一点?

回答by John La Rooy

For python2.6

对于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

对于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)

回答by ghostdog74

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

Or if you file is not too big,

或者如果你的文件不是太大,

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)

回答by Mark Tolonen

Read the whole file as a list of lines, then replace the lines you want to delete with a new list of lines:

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

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()

Note that list slicing is zero-based, and [2:4] means "element 2 up to but not including element 4".

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

回答by Ignacio Vazquez-Abrams

Open a second file to write to, read and then write the lines you want to copy over, write the new lines, read the lines you want to skip, then copy the rest.

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

回答by inspectorG4dget

import os
i = open(inputFilePath, 'r')
o = open(inputFilePath+"New", 'w')

lineNo = 0
for line in input:
    lineNo += 1
    if lineNo != 3:
        o.write(line)
    else:
        o.write(myNewLines)

i.close()
o.close()
os.remove(inputFilePath)
os.rename(inputFilePath+"New", inputFilePath)

Hope this helps

希望这可以帮助

回答by Anurag Uniyal

There are be several ways to achieve that

有几种方法可以实现

  1. if you file is small and your lines unique, you can just read whole file and replace the line e.g.

    f.read().replace("third line", "new line1\nnew line2\nnew line3")

  2. But if the file is big or lines not unqiue, just read thru file line by line, and output each line but at third line output three different lines

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

    f.read().replace("第三行", "new line1\nnew line2\nnew line3")

  2. 但如果文件很大或行不统一,只需逐行读取文件,并输出每一行,但在第三行输出三行不同

e.g

例如

for i, line in enumerate(f):
    if i == 2:
        o.write(myThreelines)
    else:
        o.write(line)