从关闭的python文件列表中打开文件时出现问题?

2024-04-25 14:11:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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


Tags: 文件oftextindocs列表doccount
1条回答
网友
1楼 · 发布于 2024-04-25 14:11:04

file不是索引,它已经是列表中的项

因此,您可以:(关闭的文件具有.name属性)

for file in range list_of_docs:
    current_doc = open(file.name, 'r')
    ...

我认为您应该重构代码以使用文件名列表

  for filename in range list_of_filenames:
    current_doc = open(filename, 'r')
      ...
      # still need to close the file

要确保文件已关闭,请使用上下文管理器

for filename in range list_of_filenames:    
    with open(filename, 'r') as current_doc:
        text = current_doc.read()
        line = text.split()
        if word in line:
          count += 1

相关问题 更多 >