Saturday, February 8, 2020

Buku Tips dan Trik Pemrograman Python - Tree Folder dan File


Seiring dengan meningkatnya traffic dan kemudahan dalam mengelola content, kami mengucapkan banyak terima kasih kepada para pembaca setia pada blog www.softscients.web.id

Per 19 Maret 2020, kami sedang melakukan migrasi ke domain dan hosting yang lebih baik yaitu
Semoga dengan alamat domain dan hosting terbaru akan semakin memudahkan para pembaca dalam mencari materi/content. Migrasi dilakukan secara bertahap yang membutuhkan waktu yang cukup lama jadi jangan kuatir selama migrasi akan dilakukan secara hati-hati untuk memimalkan broken link


kalian bisa lanjut baca lagi di http://softscients.com/2020/03/28/buku-pemrograman-python-view-tree-folder-dan-file/



Sinopsis

Kalian tentu pernah menggunakan CLI Command Line Interface yaitu command prompt untuk melihat isi sebuah direktori/folder dan file seperti berikut menggunakan perintah \(tree\), walaupun terlihat sepele namun sangat berguna sekali kalau kalian sedang mencari file/folder secara cepat daripada menggunakan explorer.

Buku Tips dan Trik Pemrograman Python -  Tree Folder dan File

Kalian juga bisa koq menggunakan python untuk membuat tree sendiri seperti hasil berikut

Buku Tips dan Trik Pemrograman Python -  Tree Folder dan File

Modul/package yang  digunakan yaitu modul os, langsung saja kalian pelajari kode dibawah ini


import os
def showFolderTree(path,show_files=False,indentation=2,file_output=False):
    
    """
    Shows the content of a folder in a tree structure.
    path -(string)- path of the root folder we want to show.
    show_files -(boolean)-  Whether or not we want to see files listed.
                            Defaults to False.
    indentation -(int)- Indentation we want to use, defaults to 2.   
    file_output -(string)-  Path (including the name) of the file where we want
                            to save the tree.
    """
    
    
    tree = []
    
    if not show_files:
        for root, dirs, files in os.walk(path):
            level = root.replace(path, '').count(os.sep)
            indent = '|'*indentation*(level)
            tree.append('{}{}/'.format(indent,os.path.basename(root)))
    
    if show_files:
        for root, dirs, files in os.walk(path):
            level = root.replace(path, '').count(os.sep)
            indent = '|'*indentation*(level)
            tree.append('{}{}/'.format(indent,os.path.basename(root)))    
            for f in files:
                subindent='-' * indentation * (level+1)
                tree.append('{}{}'.format(subindent,f))
    
    if file_output:
        output_file = open(file_output,'w')
        for line in tree:
            output_file.write(line)
    else:
        # Default behaviour: print on screen.    
        for line in tree:
            print (line)
            
folder = 'L:/My BLOG/Ebook Pemrograman Matlab'           
showFolderTree(folder,show_files=True,indentation=6,file_output=False)

Sangat mudah bukan? Tree Folder dan File menggunakan Python, atau kalian bisa mencoba menggunakan Tkinter

Buku Tips dan Trik Pemrograman Python -  Tree Folder dan File


import os
import glob
import tkinter
from tkinter import ttk
def populate_tree(tree, node):
    if tree.set(node, "type") != 'directory':
        return

    path = tree.set(node, "fullpath")
    tree.delete(*tree.get_children(node))

    parent = tree.parent(node)
    special_dirs = [] if parent else glob.glob('.') + glob.glob('..')

    for p in special_dirs + os.listdir(path):
        ptype = None
        p = os.path.join(path, p).replace('\\', '/')
        if os.path.isdir(p): ptype = "directory"
        elif os.path.isfile(p): ptype = "file"

        fname = os.path.split(p)[1]
        id = tree.insert(node, "end", text=fname, values=[p, ptype])

        if ptype == 'directory':
            if fname not in ('.', '..'):
                tree.insert(id, 0, text="dummy")
                tree.item(id, text=fname)
        elif ptype == 'file':
            size = os.stat(p).st_size
            tree.set(id, "size", "%d bytes" % size)


def populate_roots(tree):
    dir = os.path.abspath('L:/').replace('\\', '/')
    node = tree.insert('', 'end', text=dir, values=[dir, "directory"])
    populate_tree(tree, node)

def update_tree(event):
    tree = event.widget
    populate_tree(tree, tree.focus())

def change_dir(event):
    tree = event.widget
    node = tree.focus()
    if tree.parent(node):
        path = os.path.abspath(tree.set(node, "fullpath"))
        if os.path.isdir(path):
            os.chdir(path)
            tree.delete(tree.get_children(''))
            populate_roots(tree)

def autoscroll(sbar, first, last):
    """Hide and show scrollbar as needed."""
    first, last = float(first), float(last)
    if first <= 0 and last >= 1:
        sbar.grid_remove()
    else:
        sbar.grid()
    sbar.set(first, last)

root = tkinter.Tk()
vsb = ttk.Scrollbar(orient="vertical")
hsb = ttk.Scrollbar(orient="horizontal")
tree = ttk.Treeview(root)
tree = ttk.Treeview(columns=("fullpath", "type", "size"),
    displaycolumns="size", yscrollcommand=lambda f, l: autoscroll(vsb, f, l),
    xscrollcommand=lambda f, l:autoscroll(hsb, f, l))

vsb['command'] = tree.yview
hsb['command'] = tree.xview

tree.heading("#0", text="Directory Structure", anchor='w')
tree.heading("size", text="File Size", anchor='w')
tree.column("size", stretch=0, width=100)

populate_roots(tree)
tree.bind('<<TreeviewOpen>>', update_tree)
tree.bind('<Double-Button-1>', change_dir)

# Arrange the tree and its scrollbars in the toplevel
tree.grid(column=0, row=0, sticky='nswe')
vsb.grid(column=1, row=0, sticky='ns')
hsb.grid(column=0, row=1, sticky='ew')
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)

root.mainloop()

No comments:

Post a Comment