【问题标题】:File not found error, even though file was found文件未找到错误,即使文件已找到
【发布时间】:2017-12-22 12:40:48
【问题描述】:

使用以下代码:

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(最近一次调用最后一次):文件“text_statistics.py”,行 28,在 corpus_reading_pos(corpus_name, option) 文件“text_statistics.py”,第 13 行,在 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)

【问题讨论】:

  • 您在corpus_name 中找到该文件,但您在当前工作目录中打开它。
  • 所以我的语料库包含数百个文件,我只需要访问以“.v4_gold_conll”结尾的文件并提取信息。我不知道我会怎么做...

标签: python python-3.x


【解决方案1】:

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)

【讨论】:

  • 谢谢你,这行得通,但是替换这部分后,它只从一个文件中提取了令牌,而不是所有文件??
  • 现在我遇到了一个问题,它只打开了 7 个文件就停止了。文件夹和子文件夹中应该有 172 个文件。
  • 好吧,它没有理由在七个文件之后“停止”。您确定这些文件具有正确的扩展名吗?请记住,Python 中的文件区分大小写。如果将else 添加到if 会发生什么?
  • 我要打开的文件都有相同的结尾,“.v4_gold_conll”。它们位于不同的子文件夹和子子文件夹中是否有区别?
  • 它看起来只读取最低子文件夹中的文件,而没有读取其他子文件夹中的文件。
【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 2016-06-05
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多