【问题标题】:FileNotFoundError: [Errno 2] No such file or directory despite the file definitely existingFileNotFoundError: [Errno 2] 尽管文件确实存在,但没有这样的文件或目录
【发布时间】:2019-02-27 22:07:01
【问题描述】:

我一直在编写这段代码,试图在一个目录中打开多个文件。该目录包含 10 个文本文件。我想打开每个文件,对其做一些事情(即删除停用词)并将转换后的文本输出到不同目录中的新文件中。但是,我有这个问题:

FileNotFoundError: [Errno 2] 没有这样的文件或目录:'1980'

该文件肯定存在于目录中,我一直在给出绝对路径。我在打开文件之前查看了当前的工作目录,它没有返回我给它的绝对路径,而是这个项目所在的目录。任何帮助获取代码以打开必要的文件并将结果写入输出文件将不胜感激!这是我的代码:

path = 'C:/Users/User/Desktop/mini_mouse'
output = 'C:/Users/User/Desktop/filter_mini_mouse/mouse'
for root, dir, files in os.walk(path):
    for file in files:
        print(os.getcwd())
        with open(file, 'r') as f, open('NLTK-stop-word-list', 'r') as f2:
            x = ''
            mouse_file = f.read().split()  # reads file and splits it into a list
            stopwords = f2.read().split()
            x = (' '.join(i for i in mouse_file if i.lower() not in (x.lower() for x in stopwords)))
            with open('out', 'w') as output_file:
                output_file.write((' '.join(i for i in mouse_file if i.lower() not in (x.lower() for x in stopwords))))

【问题讨论】:

  • 尝试将目录名称改成字母名称而不是数字,然后再执行,我猜是问题所在。
  • “字母名称而不是数字”是什么意思?
  • 根据您输入的错误,该目录名为“1980”(FileNotFoundError: [Errno 2] No such file or directory: '1980'),将目录名称更改为“nineteen_eighty” ' 并尝试再次运行它
  • 不,这似乎不起作用。错误现在说:(FileNotFoundError: [Errno 2] No such file or directory: 'nineteen_eighty')

标签: python file path


【解决方案1】:

你在 Windows 上吗?每当我在 Windows 上执行绝对路径时,我都需要使用反斜杠()而不是正斜杠(/)进行路径。

【讨论】:

  • 不,不幸的是,这也不起作用。我收到此错误:path = 'C:\Users\User\Desktop\mini_mouse' ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
【解决方案2】:

您的代码的问题在于'1980' 不是文件的完整路径,它只是string。您应该像下面这样附加路径的其余部分,例如使用 path.join:

with open(os.path.join(path, file), 'r') as f, open(os.path.join(path, 'NLTK-stop-word-list'), 'r') as f2:

然后 Python 将能够找到该文件并以读取模式打开它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2022-11-13
    • 2019-11-03
    • 2021-08-24
    • 2021-03-07
    相关资源
    最近更新 更多