Home > Backend Development > Python Tutorial > Why Does Python Raise a FileNotFoundError When Opening Files Listed by `os.listdir`?

Why Does Python Raise a FileNotFoundError When Opening Files Listed by `os.listdir`?

Mary-Kate Olsen
Release: 2024-11-20 16:56:17
Original
648 people have browsed it

Why Does Python Raise a FileNotFoundError When Opening Files Listed by `os.listdir`?

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template