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
Release: 2024-12-21 17:22:16
Original
869 people have browsed it

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

Using os.listdir:

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

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

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!

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