Python脚本从文件中删除包含数组中单词的行
我有一个脚本,它可以找到文件中我想要删除的行,这些行是根据一个数组来判断的,但它并没有真正删除这些行。
我应该改哪里呢?
sourcefile = "C:\\Python25\\PC_New.txt"
filename2 = "C:\\Python25\\PC_reduced.txt"
offending = ["Exception","Integer","RuntimeException"]
def fixup( filename ):
print "fixup ", filename
fin = open( filename )
fout = open( filename2 , "w")
for line in fin.readlines():
for item in offending:
print "got one",line
line = line.replace( item, "MUST DELETE" )
line=line.strip()
fout.write(line)
fin.close()
fout.close()
fixup(sourcefile)
4 个回答
0
你没有把内容写入输出文件。另外,我建议用“in”来检查字符串是否在这一行中。下面是修改过的脚本(没有测试过):
sourcefile = "C:\\Python25\\PC_New.txt"
filename2 = "C:\\Python25\\PC_reduced.txt"
offending = ["Exception","Integer","RuntimeException"]
def fixup( filename ):
print "fixup ", filename
fin = open( filename )
fout = open( filename2 , "w")
for line in fin.readlines():
if not offending in line:
# There are no offending words in this line
# write it to the output file
fout.write(line)
fin.close()
fout.close()
fixup(sourcefile)
2
基本的做法是把输入文件的内容复制到输出文件,但要做一些修改。在你的情况下,修改非常简单:就是把你不想要的行删掉。
一旦你把复制的文件安全地写好了,就可以删除原来的文件,然后用 'os.rename()' 把临时文件改成原文件的名字。我喜欢把临时文件放在和原文件同一个文件夹里,这样可以确保我有权限在那个文件夹里写东西,而且我也不确定 os.rename()
是否能把文件从一个地方移动到另一个地方。
你不需要写 for line in fin.readlines()
; 只需要写 for line in fin
就可以了。当你用 .readlines()
的时候,你是在告诉 Python 一次性把输入文件的每一行都读到内存里;而如果你只用 fin
,那就是每次读一行。
下面是你修改过的代码,做了这些更改。
sourcefile = "C:\\Python25\\PC_New.txt"
filename2 = "C:\\Python25\\PC_reduced.txt"
offending = ["Exception","Integer","RuntimeException"]
def line_offends(line, offending):
for word in line.split():
if word in offending:
return True
return False
def fixup( filename ):
print "fixup ", filename
fin = open( filename )
fout = open( filename2 , "w")
for line in fin:
if line_offends(line, offending):
continue
fout.write(line)
fin.close()
fout.close()
#os.rename() left as an exercise for the student
fixup(sourcefile)
如果 line_offends()
返回 True,我们就执行 continue
,这样循环就会继续,而不会执行后面的部分。这意味着这一行不会被写入。对于这个简单的例子,其实这样做也可以:
for line in fin:
if not line_offends(line, offending):
fout.write(line)
我用 continue
是因为在主循环中通常会有一些复杂的工作,如果测试为真,你就想跳过所有这些工作。在我看来,简单地说“如果这一行不想要,就继续”比把一大堆东西缩进到一个 if
里要好,尤其是这种情况可能很少见。
5
sourcefile = "C:\\Python25\\PC_New.txt"
filename2 = "C:\\Python25\\PC_reduced.txt"
offending = ["Exception","Integer","RuntimeException"]
def fixup( filename ):
fin = open( filename )
fout = open( filename2 , "w")
for line in fin:
if True in [item in line for item in offending]:
continue
fout.write(line)
fin.close()
fout.close()
fixup(sourcefile)
for line in fin:
if not True in [item in line for item in offending]:
fout.write(line)
编辑: 或者更好的是: