Directory and file structure showing in Treeview

Showing directory and file structure in Treeview()
We can use askdirectory() to select any directory in your system. After selecting the directory we can collect the sub-directories and files inside the selected directory by using os.walk(). Here the variable path holds the system path as string.
dirnames=next(os.walk(path))[1] # list of directories 
    files=next(os.walk(path))[2] # list of files 

Using Treeview

By using Treeview we can display the directories and files of the user selected path.
First we will delete all items of the Treeview before adding new files or directories.
    for item in trv.get_children():
        trv.delete(item)

Showing directories with child node

We can check here how to add child node to a parent row of Treeview. On expansion of parent node the files inside the parent ( main directory ) is shown. Watch the + sign against each directory.
Watch how the value of variable i is used as iid of parent item and same is used as parent iid while inserting the child items.
Each child item has different value of iid ( value of f2i ) . We used str() to convert integer value of f2i to string while assigning unique iid to child nodes.
i=1
    f2i=1 #sub directory id 
    for d in dirnames:
        trv.insert("", 'end',iid=i,values =d)
        path2=path+'/'+d # Path for sub directory 
        #print(path2)
        files2=next(os.walk(path2))[2] # file list of Sub directory 
        for f2 in files2:  # list of files 
            #print(f2)
            trv.insert(i, 'end',iid='sub'+str(f2i),values ="-" + f2)
            f2i=f2i+1
        i=i+1

Displaying the files

After showing the directories with child nodes, we can display all the files inside the user selected directory.
for f in files:  # list of files 
	trv.insert("", 'end',iid=i,values =f)
    i=i+1
Note how the value of i is maintained across the directory listing and then file listing so unique iid values can be assigned to each item in Treeview.

Tkinter showing directory and file structure in Treeview of the user selected path using filedialog


Full code is here


Above code ( same code ) is displayed here for better understanding.
import tkinter as tk
from tkinter import filedialog
import os
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("400x300")  # Size of the window 
my_w.title("www.plus2net.com")  #  title
my_dir='' # string to hold directory path 
def my_fun(): 
    path = filedialog.askdirectory() # select directory 
    l1.config(text=path) # update the text of Label with directory path
    root=next(os.walk(path))[0] # path 
    dirnames=next(os.walk(path))[1] # list of directories 
    files=next(os.walk(path))[2] # list of files 
    print(root) # D:\my_dir\my_dir0
    print(dirnames) # ['my_dir1']
    print(files) # ['my_file0.txt']
    for item in trv.get_children():
        trv.delete(item)
    i=1
    f2i=1 #sub directory id 
    for d in dirnames:
        trv.insert("", 'end',iid=i,values =d)
        path2=path+'/'+d # Path for sub directory 
        #print(path2)
        files2=next(os.walk(path2))[2] # file list of Sub directory 
        for f2 in files2:  # list of files 
            #print(f2)
            trv.insert(i, 'end',iid='sub'+str(f2i),values ="-" + f2)
            f2i=f2i+1
        i=i+1

    for f in files:  # list of files 
        trv.insert("", 'end',iid=i,values =f)
        i=i+1

b1=tk.Button(my_w,text='Select directory',font=22,
    command=lambda:my_fun(),bg='lightgreen')
b1.grid(row=0,column=0,padx=5,pady=10)

l1=tk.Label(my_w,text=my_dir,bg='yellow',font=16)
l1.grid(row=0,column=1,padx=0)

trv=ttk.Treeview(my_w,selectmode='browse',height=9)
trv.grid(row=1,column=0,columnspan=2,padx=10,pady=5)
trv["columns"]=("1")
trv['show']='tree headings'
trv.column("#0", width = 20, anchor ='c')
trv.column("1",width=300,anchor='w')
trv.heading("#0", text ="#")
trv.heading("1",text="Name",anchor='w')

my_w.mainloop()  # Keep the window open

Part II: Showing file explorer type file names, Date Modified, Type and size

Directory Listing with Modified date, size and type  using Treeview
We can display all files and directories of a directory along with the Date Modified , Type of file and size in bytes. Treeview will be used to show details in rows.

Filedialog is used to browse the local file system and select the directory.

File modification time, file type and file size using os library.

from tkinter import ttk
import tkinter as tk
from tkinter import filedialog
import os
from datetime import datetime
# Creating tkinter my_w
my_w = tk.Tk()
my_w.geometry("600x480") 
my_w.title("www.plus2net.com")  

b1=tk.Button(my_w,text='Select directory',font=22,
    command=lambda:my_fun(),bg='lightgreen')
b1.grid(row=1,column=1,padx=10,pady=10)

l1=tk.Label(my_w,text='',bg='yellow',font=18)
l1.grid(row=1,column=2,padx=2,columnspan=2)
# Using treeview widget
def my_view():
    global trv
    trv = ttk.Treeview(my_w, selectmode ='browse',show='headings')
    trv.grid(row=2,column=1,columnspan=3,padx=30,pady=10)
# column identifiers 
    trv["columns"] = ("1", "2","3","4")
    trv.column("1", width = 150, anchor ='w')
    trv.column("2", width = 100, anchor ='c')
    trv.column("3", width = 100, anchor ='c')
    trv.column("4", width = 70, anchor ='c')


    trv.heading(1, text ="Name",anchor='w')
    trv.heading(2, text ="Type",anchor='c')
    trv.heading(3, text ="Date Modified",anchor='c')
    trv.heading(4, text ="Size",anchor='c')

def my_fun(): 
    my_dir = filedialog.askdirectory() # select directory 
    l1.config(text=my_dir) # update the text of Label with directory path
    my_view()
    my_insert(my_dir)
def my_insert(path):
    global trv
    #path = "E:\\testing\\images\\test3.png"  # Directory Path
    
    files=os.listdir(path)
    i=1
    for f in files:
        f_path=path+'\\'+f # Path with file name
        t_stamp=os.path.getmtime(f_path) # for file modificaton time
        #t_stamp=os.path.getctime(path) # for file Creation time
        f_name,f_extension=os.path.splitext(f_path) # get file extension
        size=os.path.getsize(f_path) # size of file in bytes 
        dt_mod = datetime.fromtimestamp(t_stamp) # date object 
        #print('File Modified on:', dt_mod)  # Prting date and time 
        m_date = datetime.strftime(dt_mod, '%Y-%m-%d') # Change format 
        #print(f, f_extension, m_date,size)
        trv.insert("",'end',iid=i,text=i,values=(f, f_extension, m_date,size))
        i=i+1
        vs = ttk.Scrollbar(my_w,orient="vertical", command=trv.yview) # scrollbar
        trv.configure(yscrollcommand=vs.set)  # connect to Treeview
        vs.grid(row=2,column=4,sticky='ns') # Place on grid 
my_w.mainloop()
Tkinter filedialog.askopenfile() Operating system Interface Upload and display image file Treeview Columns sorting using Pandas DatraFrame
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer