Python provides several methods for traversing directories and retrieving a list of files. Here are three common approaches:
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))]
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.
import os f = [] for (dirpath, dirnames, filenames) in os.walk(mypath): f.extend(filenames) break
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.
import os filenames = next(os.walk(mypath), (None, None, []))[2]
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!