Home >Backend Development >Python Tutorial >How Can I Find All .txt Files in a Directory Using Python?

How Can I Find All .txt Files in a Directory Using Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-21 17:22:16870browse

How Can I Find All .txt Files in a Directory Using Python?

Find All Files with .txt Extension in Python

Finding all files with a specific extension in a directory is a common task in programming. Python provides several methods to accomplish this, as you'll see below.

To locate all files with the .txt extension:

Using glob:

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

Using os.listdir:

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

Using os.walk:

This method is suitable for traversing a directory and its subdirectories:

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

Choose the method that best suits your specific requirements.

The above is the detailed content of How Can I Find All .txt 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