Python线卸妆

时间:2010-09-30 21:22:51

标签: python

嗨我有一个大文件,我想删除包含文本ALL的行,并打印没有空格的文件,只剩下剩下的行。我开始了一个程序

sourcefile = open('C:\\scoresfinal.txt', 'r')
filename2 = open('C:\\nohet.txt', 'w')

offending = ["HET"]

def fixup( filename ): 
    fin = open( filename ) 
    fout = open( filename2 , "w") 
    for line in fin.readlines(): 
        if True in [item in line for item in offending]:
            continue
        fout.write(line)
    fin.close() 
    fout.close() 

fixup(sourcefile)

但它不起作用。有什么帮助吗?

这是我的错误:

Traceback (most recent call last):
  File "C:/Python Make Small File/hetcut2.py", line 18, in <module>
    fixup(sourcefile)
  File "C:/Python Make Small File/hetcut2.py", line 9, in fixup
    fin = open( filename )
    TypeError: coercing to Unicode: need string or buffer, file found

4 个答案:

答案 0 :(得分:1)

sourcefile = open('C:\\scoresfinal.txt', 'r')

sourcefile定义为文件对象。所以

fixup(sourcefile)

sourcefile指定为filename函数中局部变量fixup的值。

open(filename)期望一个字符串命名文件或文件路径时,调用open会尝试打开一个已经打开的文件对象。

您可以通过这种方式修复代码:

sourcefile = 'C:\\scoresfinal.txt'
filename2 = 'C:\\nohet.txt'

offending = ["HET"]

def fixup( filename ): 
    with open( filename ) as fin:
        with open( filename2 , "w") as fout:
            for line in fin: 
                if any(item in line for item in offending):
                    continue
                fout.write(line)
fixup(sourcefile)

with open(...) as f语句在Python2.6或更高版本中可用。 在Python2.5中,如果放入

,则可以使用with语句
from __future__ import with_statement

这样做的好处是可以保证用Python退出文件句柄退出with - 块。 (注意,对fin.close()和fout.close()的显式调用已被删除。)

使用with不是解决您的直接问题所必需的,但它是Python中未来的标准习惯用法,因此您可能习惯它。

答案 1 :(得分:1)

首先,打开文件并将句柄存储在filename2内。然后在函数中,你试图使用filename2作为 - well - 文件名,而不是它已经打开的文件的句柄。

如果您希望这样做,则必须将filename2设置为实际文件名:

filename2 = 'C:\\nohet.txt'

此外,您应该考虑将目标路径名移动到函数参数中,因此它不依赖于某些全局变量。

哦,同样适用于sourcefile,它也是一个文件句柄,但你的函数也试图用作文件名。

编辑:

像这样:

def fixup( source, target, badWords ):
    fin = open( source ) 
    fout = open( target , "w" )

    for line in fin:
        if any( ( word in line ) for word in badWords ):
            continue
        fout.write( line )

    fin.close() 
    fout.close() 

offending = ["HET"]
fixup( 'C:\\scoresfinal.txt', 'C:\\nohet.txt', offending )

答案 2 :(得分:0)

2)sourcefile和filename2是文件,而不是字符串。

答案 3 :(得分:0)

问题已经得到解答(你是“打开文件两次”)但我想我应该指出你可以在某种程度上整理代码:

def fixup( filename ): 
    with fin as open(filename), fout as open(filename2 , "w") 
        for line in fin:
            if not any(word in line for word in offending):
                fout.write(line)

此外,您应该考虑使用更好的变量名称。 fixupfilenamefilename2(唉!)并不是很有启发性。

相关问题