FileNotFoundError when Iterating Over Files with os.listdir
When iterating over files in a directory using os.listdir, it's possible to encounter a FileNotFoundError even though the file exists. This is because os.listdir only returns the file name, not the full path to the file.
import os path = r'E:/somedir' for filename in os.listdir(path): f = open(filename, 'r') ... # process the file
In this example, Python throws a FileNotFoundError even though the file exists because filename only contains the file name, such as 'foo.txt', instead of the full path, such as 'E:/somedir/foo.txt'.
To resolve this issue, use os.path.join 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
Additionally, it's recommended to use a context manager with statement for opening files, as it ensures the file is closed properly when finished.
The above is the detailed content of Why Does `os.listdir` Cause `FileNotFoundError` When Opening Files?. For more information, please follow other related articles on the PHP Chinese website!