首页 > 解决方案 > 尝试打开文件以在 Python 3 中读取时出现 FileNotFoundError

问题描述

我正在使用 OS 模块打开一个文件进行读取,但我收到了 FileNotFoundError。

我在尝试着

当我尝试打开时,出现以下错误:

 File "parse_mda_SIC.py", line 16, in <module>
     f = open(file, 'r')
FileNotFoundError: [Errno 2] No such file or directory:        
'mda_3357_2017-03-08_1000230_000143774917004005__3357.txt'

我怀疑问题出在“文件”变量或它是一个目录下的事实,但混淆了为什么当我使用操作系统来解决该较低目录时会发生这种情况。

我有以下代码:

working_dir = "data/"

for file in os.listdir(working_dir):
    if (file.find("mda") != -1):
        SIC = re.findall("__(\d+)", file)
        f = open(file, 'r')

我希望能够毫无问题地打开文件,然后从数据中创建我的列表。谢谢你的帮助。

标签: pythonpython-3.xpython-os

解决方案


这应该适合你。您需要附加该目录,因为它仅将其视为代码顶部的文件名,并且只会在您的代码所在的目录中查找该文件名。

for file in os.listdir(working_dir):
    if (file.find("mda") != -1):
        SIC = re.findall("__(\d+)", file)
        f = open(os.path.join(working_dir, file), 'r')

此外,使用上下文管理器打开文件也是一个好习惯,with因为它会在不再需要文件时处理关闭文件:

for file in os.listdir(working_dir):
    if (file.find("mda") != -1):
        SIC = re.findall("__(\d+)", file)
        with open(os.path.join(working_dir, file), 'r') as f:
            # do stuff with f here

推荐阅读