尝试读取目录python中的文件时没有这样的文件或目录 [英] No such file or directory while trying to read files in a directory python

查看:45
本文介绍了尝试读取目录python中的文件时没有这样的文件或目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码,它列出了目录中的文件,并用我的函数解析每个文件.

I have this code which lists the files in the directory and parses each one of them with my function.

paths = []
for filename in os.listdir(r"C:\Program Files (x86)\Folder\Folder"):
    with open(filename) as f:            
        paths.append(parse_file(f))

我收到错误:

  File "find.py", line 21, in <module>
    with open(filename) as f:
IOError: [Errno 2] No such file or directory: 'file.txt'

这个错误表明它看到了file.txt,因为它存在于我在os.listdir 中指定的文件夹中,我在那里有更多的文件.如果我删除 file.txt,它会在不同的文件中显示错误.

This error shows that it saw file.txt because it exist in the folder I specified in os.listdir, I have many more files there. If I delete file.txt it will show the error on a different file.

我还尝试将文件移动到桌面上的目录中,脚本运行良好.

I also tried to move the files to a directory in my desktop and the script worked fine.

我不明白是什么问题.我对python很陌生,所以如果它的问题很愚蠢,请原谅我.谢谢!

What is the issue I don't understand. I am pretty new to python so forgive me if its dumb question. Thank you!

推荐答案

os.listdir() 返回文件名,而不是路径.将它们与目录名称连接起来以形成绝对路径:

os.listdir() returns filenames, not paths. Join them with the directory name to make absolute paths:

path = r"C:\Program Files (x86)\Folder\Folder"
for filename in os.listdir(path):
    with open(os.path.join(path, filename)) as f:            

这篇关于尝试读取目录python中的文件时没有这样的文件或目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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