FAQs

Python FAQs

python
faq
Author

ivansaul

Published

January 3, 2023

This post lists the Python Programming FAQ (Frequently Asked Questions and answers) also a collection of many trouble shooting use cases.

Set the recursive attribute of a glob() method to True to list text files from subdirectories.

import glob

# absolute path to search all text files inside a specific folder
path = r'E:/account/**/*.txt'
files = glob.glob(path, recursive=True)
print(files)

Using os.walk()

import os

# list to store txt files
res = []
# os.walk() returns subdirectories, file from current directory and 
# And follow next directory from subdirectory list recursively until last directory
for root, dirs, files in os.walk(r"E:\demos\files_demos\account"):
    for file in files:
        if file.endswith(".txt"):
            res.append(os.path.join(root, file))
print(res)