Skip to main content
 首页 » 编程设计

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

2025年05月04日15jyk

我有以下脚本,它根据一个数组识别我想要删除的文件中的行,但不删除它们。

我应该改变什么?

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) 

请您参考如下方法:

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)