Aar*_*hra 6 python error-handling file-not-found
我试图遍历这样的目录中的文件:
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)
那么,这里出了什么问题?
这是因为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
Run Code Online (Sandbox Code Playgroud)
(此外,您没有关闭文件;with块将自动处理它)。
| 归档时间: |
|
| 查看次数: |
23356 次 |
| 最近记录: |