我有以下脚本,它根据数组标识要删除的文件中的行,但不删除它们。
我该换什么?
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)
编辑:甚至更好:
您没有将其写入输出文件。另外,我将使用“in”来检查行中是否存在字符串。请参阅下面的修改脚本(未测试):
基本策略是将输入文件的副本写入输出文件,但要进行更改。在您的例子中,更改非常简单:您只需省略不需要的行。
安全写入副本后,可以删除原始文件,并使用“os.rename()”将临时文件重命名为原始文件名。我喜欢在原始文件所在的目录中写入临时文件,以确保我有权在该目录中写入文件,因为我不知道
os.rename()
是否可以将文件从一个卷移动到另一个卷。你不需要说
for line in fin.readlines()
;说for line in fin
就足够了。当您使用.readlines()
时,您告诉Python一次将输入文件的每一行读取到内存中;当您仅使用fin
时,您一次读取一行。这是您的代码,修改后可以执行这些更改。
如果
line_offends()
返回True,则执行continue
,循环继续,而不执行下一部分。这意味着这句话永远不会被写下来。对于这个简单的例子,这样做也同样好:我用
continue
编写它,因为在主循环中经常会有一些非琐碎的工作要做,如果测试是真的,您需要避免所有这些工作。不过,对于可能非常罕见的情况,最好使用一个简单的“如果这一行不需要,请继续”而不是在if
中缩进一大堆内容。相关问题 更多 >
编程相关推荐