首页 > 解决方案 > Python 脚本仅读取 100 个第一个文件

问题描述

我有一个包含 616 个文件的文件夹,但我的脚本只读取前 100 个文件。我需要更改哪些设置才能让它全部读取?这可能是相关的,我正在使用 Anaconda Navigator 的 Jupyter Notebook。

这是我的代码:

import re
import string
from collections import Counter
import os
import glob

def word_count(file_tokens):
    for word in file_tokens:
        count = Counter(file_tokens)
    return count

files_list = glob.glob("german/test/*/negative/*")
print(files_list)
for path in files_list:
    corpus, tache, classe, file_name = path.split("\\")
    file = open(path, mode="r", encoding="utf-8")
    read_file = file.read()

    ##lowercase
    file_clean = read_file.lower()


    ##tokenize
    file_tokens = file_clean.split()

    ##word count and sort
    print(word_count(file_tokens))

标签: pythonword-frequency

解决方案


您可能在系统中达到了一些最大打开文件限制。您可以close在循环结束时使用每个文件,也可以在循环中使用上下文管理器:

with open(path, mode="r", encoding="utf-8") as file:
    ....

推荐阅读