python从fi中删除“许多”行

2024-04-25 09:33:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从python中的文件中删除特定的行号,例如

/食品filename.txt4 5 2919

其中4 5和2919是行号

我想做的是:

for i in range(len(sys.argv)):
    if i>1: # Avoiding sys.argv[0,1]
        newlist.append(int(sys.argv[i]))

然后:

^{pr2}$

它打印原始文件中的所有行(中间有空格)


Tags: 文件in食品forlenifsysrange
3条回答

你可以试试这样的方法:

import sys
import os
filename= sys.argv[1]
lines = [int(x) for x in sys.argv[2:]]

#open two files one for reading and one for writing

with open(filename) as f,open("newfile","w") as f2:

#use enumerate to get the line as well as line number, use enumerate(f,1) to start index from 1
    for i,line in enumerate(f):  
        if i not in lines:     #`if i not in lines` is more clear than `if not i in line`
            f2.write(line)   
os.rename("newfile",filename)  #rename the newfile to original one    

注意,为了生成临时文件,最好使用^{}模块。在

import sys
# assumes line numbering starts with 1
# enumerate() starts with zero, so we subtract 1 from each line argument
omitlines = set(int(arg)-1 for arg in sys.argv[2:] if int(arg) > 0)
with open(sys.argv[1]) as fp:
    filteredlines = (line for n,line in enumerate(fp) if n not in omitlines)
    sys.stdout.writelines(filteredlines)

您可以使用^{}来确定行号:

import sys
exclude = set(map(int, sys.argv[2:]))
with open(sys.argv[1]) as f:
    for num,line in enumerate(f, start=1):
        if num not in exclude:
            sys.stdout.write(line)

如果从0开始计数,则可以删除start=1。在上述代码中,行号从1开始:

^{pr2}$

如果要将内容写入文件本身,请将其写入temporary file,而不是系统标准输出,然后将rename转换为原始文件名(或在命令行中使用sponge),如下所示:

import os
import sys
from tempfile import NamedTemporaryFile
exclude = set(map(int, sys.argv[2:]))
with NamedTemporaryFile('w', delete=False) as outf:
    with open(sys.argv[1]) as inf:
        outf.writelines(line for n,line in enumerate(inf, 1) if n not in exclude)
    os.rename(outf.name, sys.argv[1])

相关问题 更多 >