No such file or directory while trying to read files in a directory python

谁都会走 提交于 2019-11-30 10:01:33

问题


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))

I am getting the error:

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

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


回答1:


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:            


来源:https://stackoverflow.com/questions/15535188/no-such-file-or-directory-while-trying-to-read-files-in-a-directory-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!