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

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

Barbara Streisand
Release: 2024-11-20 03:54:01
Original
873 people have browsed it

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

FileNotFoundError when Iterating Over Files with os.listdir

When iterating over files in a directory using os.listdir, it's possible to encounter a FileNotFoundError even though the file exists. This is because os.listdir only returns the file name, not the full path to the file.

import os

path = r'E:/somedir'

for filename in os.listdir(path):
    f = open(filename, 'r')
    ... # process the file
Copy after login

In this example, Python throws a FileNotFoundError even though the file exists because filename only contains the file name, such as 'foo.txt', instead of the full path, such as 'E:/somedir/foo.txt'.

To resolve this issue, use os.path.join 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

Additionally, it's recommended to use a context manager with statement for opening files, as it ensures the file is closed properly when finished.

The above is the detailed content of Why Does `os.listdir` Cause `FileNotFoundError` 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template