No such file or directory while trying to read fil

2020-02-16 03:07发布

问题:

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: