python删除“许多"文件中的行 [英] python remove "many" lines from file
本文介绍了python删除“许多"文件中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试以
./foo.py filename.txt 4 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]))
然后:
count=0
generic_loop{
bar=file.readline()
count+=1
if not count in newlist:
print bar
}
它打印原始文件中的所有行(中间有空格)
it prints all the lines in original file (with blank spaces in between)
推荐答案
您可以尝试执行以下操作:
You can try something like this:
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
请注意,为了生成临时文件,最好使用 tempfile
模块.
Note that for the generation of temporary files it's better to use tempfile
module.
这篇关于python删除“许多"文件中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文