找不到文件错误,即使找到了文件

2024-06-10 15:16:30 发布

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

使用以下代码:

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个文件。在

^{pr2}$

Tags: 文件代码nameinforiflinecorpus
2条回答

您必须将root与文件名连接起来。在

for root, dirs, files in os.walk(corpus_name):
    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("#")
            ]
            print(tokens)

file只是没有目录的文件,在代码中是root。试试这个:

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

另外,最好使用with打开文件,而不要使用file作为变量名,从而隐藏内置类型。另外,根据您的评论判断,您可能应该扩展标记列表(使用+=而不是=):

^{pr2}$

相关问题 更多 >