Home >Backend Development >Python Tutorial >How to List Only Files in a Directory Using Python?

How to List Only Files in a Directory Using Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 16:30:17752browse

How to List Only Files in a Directory Using Python?

Listing Files in a Directory in Python

Listing all files in a directory is a common task in Python programming. To accomplish this, you have several options.

One approach is to use the os.listdir() function. This function returns a list of all files and directories in the specified directory. However, it does not distinguish between files and directories. To list only files, you can use the os.path.isfile() function.

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))]

Another option is to use the os.walk() function. This function yields two lists for each directory it visits: one for files and one for directories.

from os import walk

mypath = "/path/to/directory"
f = []

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

You can also use a shorter version of this code:

from os import walk

mypath = "/path/to/directory"
filenames = next(walk(mypath), (None, None, []))[2]  # [] if no file

These options provide various ways to list all files in a directory in Python. Choose the one that best suits your specific needs.

The above is the detailed content of How to 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