Python为os.listdir返回的文件名提供FileNotFoundError [英] Python giving FileNotFoundError for file name returned by os.listdir

查看:546
本文介绍了Python为os.listdir返回的文件名提供FileNotFoundError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was trying to iterate over the files in a directory like this:

import os

path = r'E:/somedir'

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

但是Python抛出 FileNotFoundError 尽管该文件存在:

But Python was throwing FileNotFoundError even though the file exists:

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'

那么这里出什么问题了?

So what is wrong here?

推荐答案

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

It is because os.listdir does not return the full path to the file, only the filename part; that is 'foo.txt', when open would want 'E:/somedir/foo.txt' because the file does not exist in the current directory.

使用 os.path.join 将目录添加到您的文件名之前:

Use os.path.join to prepend the directory to your filename:

path = r'E:/somedir'

for filename in os.listdir(path):
    with open(os.path.join(path, filename)) as f:
        ... # process the file

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

(Also, you are not closing the file; the with block will take care of it automatically).

这篇关于Python为os.listdir返回的文件名提供FileNotFoundError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆