Home >Backend Development >Python Tutorial >How Can I Efficiently List Only Files in a Directory Using Python?

How Can I Efficiently List Only Files in a Directory Using Python?

DDD
DDDOriginal
2025-01-01 12:31:11873browse

How Can I Efficiently List Only Files in a Directory Using Python?

Getting Files From a Directory

Retrieving a directory's file list is a common task in Python programming. One way to do this is using os.listdir(), which returns all items within a directory, including both files and directories.

Approach 1: Using os.path.isfile()

To list only files, use os.path.isfile():

from os import listdir
from os.path import isfile, join
mypath = 'path/to/directory'
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

Approach 2: Using os.walk()

os.walk() iterates over a directory and its subdirectories, returning a tuple for each directory it visits. This tuple contains three lists: one for files, one for directories, and one for the current directory itself.

from os import walk
mypath = 'path/to/directory'
filenames = next(walk(mypath), (None, None, []))[2]  # [] if no files

This approach provides a more complete representation of the directory structure. To list files in only the current directory, break the loop after the first iteration:

from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break

The above is the detailed content of How Can I Efficiently List Only Files in a Directory Using Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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