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
Release: 2024-12-20 11:17:16
Original
420 people have browsed it

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)
Copy after login

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))
Copy after login

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))
Copy after login

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!

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