相关疑难解决方法(0)

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

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

import os

path = r'E:/somedir'

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

但是,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'
Run Code Online (Sandbox Code Playgroud)

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

python error-handling file-not-found

6
推荐指数
1
解决办法
2万
查看次数

标签 统计

error-handling ×1

file-not-found ×1

python ×1