用于从包含数组中的单词的文件中删除行的Python脚本

rom*_*sub 1 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)
Run Code Online (Sandbox Code Playgroud)

zif*_*fot 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)
Run Code Online (Sandbox Code Playgroud)

编辑:甚至更好:

for line in fin: 
    if not True in [item in line for item in offending]:
        fout.write(line)
Run Code Online (Sandbox Code Playgroud)

  • 或者:`if any(违规项目中的项目):`此外,如果你正在使用`fout.write`,那么你应该能够进行`for line in fin`. (5认同)