我有一个python列表list_of_docs
,其中包含一个关闭的.txt文件列表。我的目标是计算有多少文件包含某个单词
def contains(word):
count = 0
for file in range list_of_docs:
current_doc = open(list_of_docs[file], 'r')
text = current_doc.read()
line = text.split()
if word in line:
count += 1
调用此函数时,我不断得到错误:
TypeError: coercing to Unicode: need string or buffer, file found
list_of_docs
中的文件实际上是在代码的前面打开的。在这个方法调用期间,我关闭它们并再次打开它们,因为如果不关闭它们,我会得到一个Too many files open
错误
我如何修复这个TypeError
file
不是索引,它已经是列表中的项因此,您可以:(关闭的文件具有
.name
属性)我认为您应该重构代码以使用文件名列表
要确保文件已关闭,请使用上下文管理器
相关问题 更多 >
编程相关推荐