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

How Can I List Files in a Directory Using Python?

Mary-Kate Olsen
Release: 2024-12-27 10:43:15
Original
639 people have browsed it

How Can I List Files in a Directory Using Python?

Listing Files in a Directory in Python

Python provides several methods for traversing directories and retrieving a list of files. Here are three common approaches:

Using os.listdir() and os.path.isfile()

import os
from os.path import isfile, join

mypath = "/path/to/directory"

# Get a list of all files in the directory
onlyfiles = [f for f in os.listdir(mypath) if isfile(join(mypath, f))]
Copy after login

This method retrieves all files and directories in the specified directory. To filter out only files, isfile() is used to check if each item in the list is a file.

Using os.walk()

import os

f = []

for (dirpath, dirnames, filenames) in os.walk(mypath):
    f.extend(filenames)
    break
Copy after login

os.walk() recursively yields directories and files within the specified path. If only the current directory's files are needed, the iteration can be broken after the first yield.

Using next(os.walk())

import os

filenames = next(os.walk(mypath), (None, None, []))[2]
Copy after login

A shorter variation of using os.walk() is to use next(). It returns three lists: the current directory path, a list of subdirectories, and a list of files. The [2] index retrieves only the list of files.

The above is the detailed content of How Can I List Files in a Directory Using 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