File Not Found Error in Python When Using os.listdir
Iterating over files in a directory using os.listdir() may trigger a FileNotFoundError, even when the file exists. This error occurs because os.listdir() returns only the filename, not the full path.
Consider the following code:
import os path = r'E:/somedir' for filename in os.listdir(path): f = open(filename, 'r')
When executed, this code would generate a FileNotFoundError for the file 'foo.txt', even though it exists in the specified directory.
The problem lies in the fact that os.listdir() returns only the filename part, such as 'foo.txt'. However, the open() function requires the full path to the file, including the directory path, such as 'E:/somedir/foo.txt'.
To resolve this issue, os.path.join() can be used to prepend the directory path to the filename:
path = r'E:/somedir' for filename in os.listdir(path): with open(os.path.join(path, filename)) as f: # process the file
The with block can also be used to automatically close the file.
The above is the detailed content of Why Does `os.listdir()` Cause `FileNotFoundError` in Python When Opening Files?. For more information, please follow other related articles on the PHP Chinese website!