Home >Backend Development >Python Tutorial >How to Find All .txt Files in a Directory (and Subdirectories) in Python?

How to Find All .txt Files in a Directory (and Subdirectories) in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-20 11:17:16527browse

How to Find All .txt Files in a Directory (and Subdirectories) in Python?

Finding Files with .txt Extension in Python

Finding files with a specific extension in a directory is a common task in programming. In Python, there are several approaches to accomplish this, particularly when searching for files with the .txt extension.

Using Glob

The glob module provides a convenient way to search for files matching a certain pattern. To find all files with the .txt extension, use the following code:

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
    print(file)

Using os.listdir

Alternatively, you can use the os.listdir function to list the contents of a directory. To filter out only the .txt files, use the following code:

import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"):
        print(os.path.join("/mydir", file))

Using os.walk

If you need to traverse through nested directories, the os.walk function provides a powerful way. The following code will recursively search all subdirectories for .txt files:

import os
for root, dirs, files in os.walk("/mydir"):
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))

The above is the detailed content of How to Find All .txt Files in a Directory (and Subdirectories) in 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