Home > Backend Development > Python Tutorial > Why Do I Get a FileNotFoundError When Using os.listdir in Python?

Why Do I Get a FileNotFoundError When Using os.listdir in Python?

Linda Hamilton
Release: 2024-11-18 19:27:02
Original
312 people have browsed it

Why Do I Get a FileNotFoundError When Using os.listdir in Python?

FileNotFoundError for File Names Returned by os.listdir

In Python, when iterating through files in a directory using os.listdir, you may encounter FileNotFoundError despite the file's existence.

Cause:

os.listdir returns only the filename (e.g., 'foo.txt'), not the full path (e.g., 'E:/somedir/foo.txt'). When opening the file, the complete path is required.

Solution:

Prepend the directory path to the filename using os.path.join:

import os

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, using the with block ensures that the file is closed automatically.

The above is the detailed content of Why Do I Get a FileNotFoundError When Using os.listdir 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