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

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

DDD
Release: 2024-12-07 14:22:13
Original
558 people have browsed it

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

File Not Found Error in Python When Using os.listdir

Iterating over files in a directory using os.listdir() may trigger a FileNotFoundError, even when the file exists. This error occurs because os.listdir() returns only 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 executed, this code would generate a FileNotFoundError for the file 'foo.txt', even though it exists in the specified directory.

The problem lies in the fact that os.listdir() returns only the filename part, such as 'foo.txt'. However, the open() function requires the full path to the file, including the directory path, such as 'E:/somedir/foo.txt'.

To resolve this issue, os.path.join() can be used 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
Copy after login

The with block can also be used to automatically close the file.

The above is the detailed content of Why Does `os.listdir()` Cause `FileNotFoundError` in Python When Opening Files?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template