python - 尝试在 Python 3 中打开文件进行读取时出现 FileNotFoundError

标签 python python-3.x python-os

我正在使用操作系统模块打开文件进行读取,但收到 FileNotFoundError。

我正在努力

  • 查找给定子目录中包含单词“mda”的所有文件
  • 对于每个文件,获取文件名中两个“_”后面的字符串(表示称为 SIC 的特定代码)
  • 打开该文件进行阅读
  • 稍后将写入主文件以进行一些 Mapreduce 处理

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

 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'

我怀疑问题要么出在"file"变量上,要么出在它位于下一个目录的事实上,但很困惑为什么当我使用操作系统来寻址该较低目录时会发生这种情况。

我有以下代码:

working_dir = "data/"

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

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

最佳答案

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

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

关于python - 尝试在 Python 3 中打开文件进行读取时出现 FileNotFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55895254/

相关文章:

python - 在括号之间插入乘号

Python os.popen() 返回运行进程计数递增 1

python - 属性错误 : 'module' object has no attribute 'scandir'

python - 如何读取从 os.listdir 获取的文件内容?

使用 Docker 的 Python 脚本沙箱

Python将SFTP服务器上的文件移动到另一个文件夹

python-3.x - 如何更改音频标题?

python - 没有名为 'scipy.sparse._sparsetools' 的模块

python - 词云:代码未显示任何错误,但显示wordcloud会引发名称错误

python-3.x - 如何在python中测试jdbc连接?