Python Raises FileNotFoundError When Trying to Open File Listed by os.listdir
In Python, attempting to iterate over files in a directory using os.listdir can raise a FileNotFoundError, despite the file existing.
This is because os.listdir returns only the filename without the directory path. As a result, when open tries to access the file using the filename alone, it fails since the file is not found in the current directory.
To resolve this issue, use os.path.join to prepend the directory path to each filename returned by os.listdir:
path = r'E:/somedir' for filename in os.listdir(path): with open(os.path.join(path, filename)) as f: # process the file # Ensure file closure
Additionally, it's prudent to use a with block to automatically handle file closure.
The above is the detailed content of Why Does Python Raise a FileNotFoundError When Opening Files Listed by `os.listdir`?. For more information, please follow other related articles on the PHP Chinese website!