FileNotFoundError for File Names Returned by os.listdir
In Python, when iterating through files in a directory using os.listdir, you may encounter FileNotFoundError despite the file's existence.
Cause:
os.listdir returns only the filename (e.g., 'foo.txt'), not the full path (e.g., 'E:/somedir/foo.txt'). When opening the file, the complete path is required.
Solution:
Prepend the directory path to the filename using os.path.join:
import os path = r'E:/somedir' for filename in os.listdir(path): with open(os.path.join(path, filename)) as f: ... # process the file
Additionally, using the with block ensures that the file is closed automatically.
The above is the detailed content of Why Do I Get a FileNotFoundError When Using os.listdir in Python?. For more information, please follow other related articles on the PHP Chinese website!