Home > Backend Development > Python Tutorial > Why Does `os.listdir` Cause `FileNotFoundError` When Opening Files in Python?

Why Does `os.listdir` Cause `FileNotFoundError` When Opening Files in Python?

Susan Sarandon
Release: 2024-11-30 09:02:10
Original
537 people have browsed it

Why Does `os.listdir` Cause `FileNotFoundError` When Opening Files in Python?

Understanding FileNotFoundError Exception When Using os.listdir and open

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

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

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!

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