SoFunction
Updated on 2024-11-19

Summary of two Python implementations of traversing directories

first type

I don't know if you remember, but I've written this before in my file handling program

Python file processing program

This program only requires the os, time library

import os,time

Then you can write the traversal code

for foldername,subfolders,filenames in (bianli_dir):
    print('Current folder:'+foldername)          #Output current folder πŸ“‚
    for subfolder in subfolders:        # Iterate through the subfolders in the current folder
        print('In'+foldername+Subfolders in ':'+subfolder)
        for filename in filenames:# Iterate over files in subfolders
            print('In'+foldername+' in the file:'+filename)

The rest is a query, error reporting function, you can add to it according to their own preferences

Complete code (example)

print("Please answer the directory you want to traverse.")
bianli_dir=input(">>>")
try:
    for foldername,subfolders,filenames in (bianli_dir):
        print('Current folder:'+foldername)          #Output current folder πŸ“‚
        for subfolder in subfolders:        # Iterate through the subfolders in the current folder
            print('In'+foldername+Subfolders in ':'+subfolder)
            for filename in filenames:# Iterate over files in subfolders
                print('In'+foldername+' in the file:'+filename)
    (1)
    print(" ")
    print("Traversal complete!")
except:
    if FileNotFoundError:
        print("There is no such catalog.")
    else:
        print("This folder cannot be traversed.")

To test the program, I now have a folder called "111".

Run 。。。。。。

Success! Basic needs have been met

second type

This method is in the form of an interface to feedback the results, some people may say, the author, you use the messagebox module in tkinter not to be enough

That's true, but what if you want to traverse a particularly large folder?

Go bigger, the screen is full 。。。。。

At this point we have to think of a different way, and since we're talking about tkinter, let's use it!

briefcase

import os
import tkinter as tk
from  import *
class Tree(object):
    """Traverse the catalog."""
    def __init__(self,path):
        =()          #Creating windows
        ("Show Tree Catalog")
        ("400x400")
        =Treeview()
        ("#0",text="file")
        (width=400,height=400)
        temppath=(path)# Extract the last filename in path
        treeF=('',0,text=temppath)#1 level of catalog
        (path,treeF)
        ()
    def showtree(self,path,root):
        filelist=(path)       # Putting files from a folder into a list
        for filename in filelist:
            abspath=(path,filename)
            # Add paths to the directory tree
            treeFinside=(root,0,text=filename,values=(abspath))
            if (abspath):
                (abspath,treeFinside)

Iteration code

lujing=input("Please enter a path to traverse.")
a=Tree(lujing)

Enter the path code

master code

import os
import tkinter as tk
from  import *
class Tree(object):
    """Traverse the catalog."""
    def __init__(self,path):
        =()          #Creating windows
        ("Show Tree Catalog")
        ("400x400")
        =Treeview()
        ("#0",text="file")
        (width=400,height=400)
        temppath=(path)# Extract the last filename in path
        treeF=('',0,text=temppath)#1 level of catalog
        (path,treeF)
        ()
    def showtree(self,path,root):
        filelist=(path)       # Putting files from a folder into a list
        for filename in filelist:
            abspath=(path,filename)
            # Add paths to the directory tree
            treeFinside=(root,0,text=filename,values=(abspath))
            if (abspath):
                (abspath,treeFinside)
lujing=input("Please enter a path to traverse.")
a=Tree(lujing)

Running!

Show Tree Catalog 2024-01-31 13-11-21

run successfully

=οΌ‰

summarize

These are the two ways that python can traverse a directory, one that gives you the results as a printout, and another that gives you the results as a tkinter interface, the second of which is much more powerful and allows you to traverse any folder, no matter how big it is.

To this point this article on Python to achieve traversal of the directory of the two methods summarized in this article, more related Python traversal of the directory content, please search for my previous articles or continue to browse the following related articles I hope that you will support me more in the future!