In Python, while iterating over files in a directory using os.listdir, users may encounter a FileNotFoundError. This is because os.listdir only returns 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 running this code, Python will raise a FileNotFoundError, even though the file exists. This is because open expects the full path to the file, which is 'E:/somedir/foo.txt' when dealing with the file 'foo.txt'.
To resolve this issue, use os.path.join to prepend the directory 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
Additionally, the code can automatically close the file using a with block.
The above is the detailed content of Why Does `os.listdir` Cause `FileNotFoundError` When Opening Files in Python?. For more information, please follow other related articles on the PHP Chinese website!