Python为os.listdir返回的文件名提供FileNotFoundError

发布于 2021-01-29 15:02:06

我试图遍历这样的目录中的文件:

import os

path = r'E:/somedir'

for filename in os.listdir(path):
    f = open(filename, 'r')
    ... # process the file

但是,FileNotFoundError即使文件存在,Python仍会抛出:

Traceback (most recent call last):
  File "E:/ADMTM/TestT.py", line 6, in <module>
    f = open(filename, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'foo.txt'

那么,这里出了什么问题?

关注者
0
被浏览
83
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    这是因为os.listdir不返回文件的完整路径,仅返回文件名部分;也就是说'foo.txt',当打开时会需要,'E:/somedir/foo.txt'因为该文件在当前目录中不存在。

    用于os.path.join在目录前添加文件名:

    path = r'E:/somedir'
    
    for filename in os.listdir(path):
        with open(os.path.join(path, filename)) as f:
            ... # process the file
    

    (此外,您没有关闭文件;该with块将自动处理该文件)。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看