python - 即使找到文件,也出现文件未找到错误

标签 python python-3.x

使用以下代码:

for root, dirs, files in os.walk(corpus_name):
    for file in files:
        if file.endswith(".v4_gold_conll"):
            f= open(file)
            lines = f.readlines()
            tokens = [line.split()[3] for line in lines if line.strip() 
and not line.startswith("#")]
    print(tokens)

我收到以下错误:

Traceback (most recent call last): File "text_statistics.py", line 28, in corpus_reading_pos(corpus_name, option) File "text_statistics.py", line 13, in corpus_reading_pos f= open(file) FileNotFoundError: [Errno 2] No such file or directory: 'abc_0001.v4_gold_conll'

正如您所看到的,该文件实际上已找到,但是当我尝试打开该文件时,它...找不到它?

编辑: 使用此更新的代码,它在读取 7 个文件后停止,但有 172 个文件。

def corpus_reading_token_count(corpus_name, option="token"):
    for root, dirs, files in os.walk(corpus_name):
        tokens = []
        file_count = 0
        for file in files:
            if file.endswith(".v4_gold_conll"):
                with open((os.path.join(root, file))) as f:
                    tokens += [line.split()[3] for line in f if line.strip() and not line.startswith("#")]
                    file_count += 1
    print(tokens)
    print("File count:", file_count)

最佳答案

file 只是不带目录的文件,即代码中的 root 。试试这个:

f = open(os.path.join(root, file)))

此外,您最好使用 with 打开文件,而不是使用 file 作为变量名,从而遮蔽内置类型。另外,从您的评论来看,您可能应该扩展标记列表(使用 += 而不是 =):

tokens = []
for root, dirs, files in os.walk(corpus_name):
    for filename in files:
        if filename.endswith(".v4_gold_conll"):
            with open(os.path.join(root, filename))) as f:
                tokens += [line.split()[3] for line in f if line.strip() and not line.startswith("#")]
print(tokens)

关于python - 即使找到文件,也出现文件未找到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47941740/

相关文章:

python - Scipy-interp2d 返回的函数自动对输入参数进行排序,但不符合预期

python - STATIC_ROOT 和 MEDIA_ROOT 正确配置

python-3.x - Python/Pandas 返回找到的字符串的列和行索引

python-3.x - tkinter 的 askopenfilename 的替代方案

python - 从列表转到字典键

python - 从 pandas 数据框中获取单词列表的计数,其中每列都是单词列表

python - nltk 中的 Text.concordance() 是否可作为分布式方法用于 pyspark

Python-在找不到时更改字典键

python - 如何导入和/或引用与内置 Python 名称同名的用户定义模块

python - Python/IPython shell 中的对象字符串表示