Monday, April 21, 2025

Get a List of All Subdirectories in the Main Directory

import os

target = 'c:\\Python38-64'

report = open('specific-ext.txt', 'w')

for root, dirname, files in os.walk(target):
    for x in dirname:
        print(x)

This code recursively traverses through the target directory (in this case, c:\\Python38-64), and for each subdirectory in the target, it prints out the name of the directory.

The os.walk() function generates the file names in a directory tree by walking the tree either top-down or bottom-up. In this code, it is used to walk through the target directory and all its subdirectories.

The function returns a tuple with three values for each directory it visits during the traversal: the path to the directory, a list of its subdirectories, and a list of its files. In this code, we only loop through the subdirectories and print their names using a for loop.

Note that since we are only interested in the subdirectory names and not the files, we only loop through the dirname variable and not the files variable. 

import os

target = 'c:\\Python38-64'

report = open('specific-ext.txt', 'w')

for root, dirname, files in os.walk(target):
    for x in dirname:
        print(root + x)

The for loop iterates over the directories found in each subdirectory, and the path of the current subdirectory is concatenated with the name of the directory to obtain the full path. Finally, the full path is printed to the console.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...