File Explorer in Python using Tkinter

File Explorer in Python using Tkinter

Introduction

Welcome to copyassignment.com. In this tutorial, we are going to learn File Explorer in Python using the Tkinter module. What is basically a file explorer? A file explorer is nothing but an application that is used to manage certain files and folders on your device where we can open, edit, copy, delete and move the files and folders on the networks or the attached disks. Click here to get the complete source code.

Here we are going to build a GUI-based project File Explorer in Python using Tkinter, shutil, filedialog, and OS modules and going to understand all the necessary steps one by one to manage the files and folders in the file explorer or file manager.

Steps for creating File Explorer in Python using Tkinter

1. Importing the Modules

from tkinter import *  # import all the widgets
import os  #importing the os and shutil module
import shutil
from tkinter import messagebox as mb #import the mesassage box for displaying the messages
from tkinter import filedialog as fd  # imports the filedialog  box

In this code, we have imported all the necessary modules that are required for the file explorer operations.

  1. Tkinter -The Tkinter module all us to create the GUI window
  2. OS – The OS module allows us to perform the different operations on the files as well as on its path
  3. Shutil – The shutil module allows you to move or copy files

Here we have imported messagebox as mb and filedialog as fd where the messagebox is used to display various messages on the screen with icons and filedialog module act as a compilation of open and saves the dialog.

There is no need to install these modules separately as they come along with python.

2. Function to open a file

# defining the function to open a file
def openAFile():
    # selecting a file using askopenfilename of filedialog as fd
    files = fd.askopenfilename(
        title="Select a file of any type",filetypes=[("All files", "*.*")]
    )
    os.startfile(os.path.abspath(files))

In the above code, we have created a function openAFile() where we have selected a file with the help of the filedialog’s method askopenfilename(). We have defines filetypes as “ All types”.The startfile() method of the OS modules is used to open the file selected. To normalize the version of the file path abspath() method is used on the file that is selected.

Output:

The output of Function to open a file in File Explorer in Python using Tkinter

3. Function to copy a file

# function to copy a file
def copyAFile():
    # using the filedialog's askopenfilename() method to select the file
    copythefile = fd.askopenfilename(
        title="Select a file to copy",filetypes=[("All files", "*.*")]
    )
    # use the filedialog's askdirectory() method for selecting the directory
    dirToPaste = fd.askdirectory(title="Select the folder to paste the file")
    try:
        shutil.copy(copythefile, dirToPaste)
        mb.showinfo(title="File copied!",message="The file has been copied to the destination."
        )
    except:
        mb.showerror(title="Error!",message="File is unable to copy.Please try again!"
        )

In the above code, we have defined a function copyAFile(). In this function, we are using the askopenfilename() method of the filedialog module to select the file to be copied. The askdirectory() method allows us to select the directory where we going to paste the file. In the try-except block, we are using the copy method of the shutil module to copy the file to the destination defined. The showinfo() and showerror() methods of the messagebox module are being used to display the messages of “file copied” and “error” respectively.

Output:

Function to copy a file in File Explorer

4. Function to delete a File

# function to delete a file
def deleteAFile():
    # selecting the file using the filedialog's askopenfilename() method
    files = fd.askopenfilename(
        title="Choose a file to delete",filetypes=[("All files", "*.*")]
    )
    # delete the file using the remove() method
    os.remove(os.path.abspath(files))
    mb.showinfo(title="File deleted!", message="The selected file has been deleted.")

In the above code, we are defining a function as deleteAFile(). In this function, we are using the askopenfilename() method to select the file to be deleted from the directory. We are using the remove() method of the OS module to delete a file. The abspath() method to normalize the file path. The showinfo() method displays the desired message in File Explorer in Python.

Output:

Function to delete a File in file explorer Application in Tkinter python

5. Function to rename a file

# function to rename a file
def renameAFile():
    rename_win = Toplevel(win_root)
    rename_win.title("Rename File")
    rename_win.geometry("300x100+300+250")
    rename_win.resizable(0, 0)
    rename_win.configure(bg="#F6EAD7")

    # create a lebel
    rename_label = Label(
        rename_win,text="Enter the file name:",font=("Calibri", "8"),bg="white",fg="blue"
    )
    # placing the label on the window
    rename_label.pack(pady=4)
    rename_field = Entry(rename_win,width=26,textvariable=fileNameEntered,relief=GROOVE,font=("Calibri", "10"),bg="white",fg="blue"
    )
    # placing the entry field on the window
    rename_field.pack(pady=4, padx=4)

    # creating a button
    submitButton = Button(
        rename_win,text="Submit",command=NameSubmit,width=14,relief=GROOVE,font=("Calibri", "9"),
    bg="white",fg="blue",activebackground="#709218",activeforeground="#FFFFFF"
    )
    submitButton.pack(pady=2)


# defining a function get the file path
def showFilePath():
    files = fd.askopenfilename(title="Select the file to rename", filetypes=[("All files", "*.*")])
    return files


# defining a function that is called when we click on Submit
def NameSubmit():
    renameName = fileNameEntered.get()
    # setting the entry field to empty string
    fileNameEntered.set("")
    fileName = showFilePath()
    # creating a new file name for the file
    newFileName = os.path.join(os.path.dirname(fileName), renameName + os.path.splitext(fileName)[1])
    os.rename(fileName, newFileName)
    mb.showinfo(title="File Renamed!", message="The selected file has been renamed.")

In the above code, we have defined a function renameAFile(). In this function, we have defined a pop-up window of class Toplevel(). In this pop-up window, we have defined Label(), Entry(), and Button () widgets that allow us to enter a new name for the file that we are going to rename.

Another function showfilePath() is defined . In this, the askopenfilename() method is used to store the file path in the variable.  We are then returning the files variable.

The next function is NameSubmit() function defined is used to submit the name of the new file. The renameName variable stores the value of the fileNameEntered object using get() method. The set() method sets the value to an empty string. The os.path.join() method is used to append the directory path with the new file name that is entered along with the extension.

Output:

Function to rename a file in Python

Output:

Function to rename a file

Output:

success message

6. Function to open a Folder

# defining a function to open a folder
def openAFolder():
    # using the filedialog's askdirectory() method to select the folder
    folder1 = fd.askdirectory(title="Select Folder to open")
    os.startfile(folder1)

Here we have defined the function openAFolder(). This function uses the askdirectory() method to select the folder and the startfile() method of the OS module to open the selected folder.

Output:

Function to open a Folder in File Explorer in Python Application using Tkinter

7. Function to delete a Folder using Python file explorer

# defining a function to delete the folder
def deleteAFolder():
    folderToDelete = fd.askdirectory(title='Select Folder to delete')
    os.rmdir(folderToDelete)
    mb.showinfo("Folder Deleted!", "The selected folder has been deleted!")

In the above code the function deleteAFolder(). In this function, we have used the askdirectory() method to select the folder. The rmdir() method of the OS  module is used to remove the folder from the directory. The showinfo() method is used to display the desired message in File Explorer in Python.

Output:

Function to delete a Folder in Python

8. Function to move a folder

# defining a function to move the folder
def moveAFolder():
    folderToMove = fd.askdirectory(title='Select the folder you want to move')
    mb.showinfo(message='Folder has been selected to move. Now, select the desired destination.')
    des = fd.askdirectory(title='Destination')
    try:
        # using the move() method of the shutil module to move the folder to the requested location
        shutil.move(folderToMove, des)
        mb.showinfo("Folder moved!", 'The selected folder has been moved to the desired Location')
    except:
        mb.showerror('Error!', 'The Folder cannot be moved. Make sure that the destination exists')

In the above code snippet, we have defined the function moveAFolder(). In this function, we are using the askdirectory() method two times. First while selecting the folder from the directory using folderToMove variable and the second time while moving the folder to the destination using the des variable. We are using the try-except where we are using the move() method of the shutil library where we have defined the move method containing the source and destination for moving the folder using python file explorer.

Output:

Function to move a folder

9. Function for Listing all files in the folder

#list all files in a folder
def listFilesInFolder():
    i = 0 # Intiliazed to 0
    # using the askdirectory() method to select the folder
    folder1= fd.askdirectory(title="Select the Folder")
    files = os.listdir(os.path.abspath(folder1))
    listFilesWindow = Toplevel(win_root)
    # specifying the title of the pop-up window
    listFilesWindow.title(f'Files in {folder1}')
    listFilesWindow.geometry("300x500+300+200")
    listFilesWindow.resizable(0, 0)
    listFilesWindow.configure(bg="white")

    # creating a list box
    the_listbox = Listbox(
        listFilesWindow,selectbackground="#F24FBF",font=("Calibri", "10"),background="white"
    )
    the_listbox.place(relx=0, rely=0, relheight=1, relwidth=1)

    # creating a scroll bar
    the_scrollbar = Scrollbar(
        the_listbox,orient=VERTICAL,command=the_listbox.yview
    )
    the_scrollbar.pack(side=RIGHT, fill=Y)
    # setting the yscrollcommand parameter of the listbox's config() method
    the_listbox.config(yscrollcommand=the_scrollbar.set)

    # iterating through the files in the folder
    while i < len(files):
        # using the insert() method to insert the file details in the list box
        the_listbox.insert(END, "[" + str(i + 1) + "] " + files[i])
        i += 1
    the_listbox.insert(END, "")
    the_listbox.insert(END, "Total Files: " + str(len(files)))

In this code , we have defined the function listFilesInFolder(). In this function, we have made use of the listdir() method of the OS module and stored the list of files in the variable files. We have created a pop-up window that shows the listing of all the files in the particular folder for that we have used a Listbox() widget and the place() method to place the list on the right side using the pack() method. The while loop function iterates through each of the files and insert() method to insert the details of the file.

Output:

Function for Listing all files in the folder

10. Function for creating the main window label and buttons for File explorer in Python

if __name__ == "__main__":
    # creating an object of the Tk() class
    win_root = Tk()
    win_root.title("File Explorer")
    win_root.geometry("400x600+650+250")
    win_root.resizable(0, 0)
    win_root.configure(bg="white")

    # creating the frames using the Frame()
    header_frame = Frame(win_root, bg="#D8E9E6")
    buttons_frame = Frame(win_root, bg="skyblue")

    # using the pack() method to place the frames in the window
    header_frame.pack(fill="both")
    buttons_frame.pack(expand=TRUE, fill="both")

    # creating a label using the Label() widget
    header_label = Label(
        header_frame,text="File Explorer",font=("Calibri", "16"),bg="white",fg="blue"
    )

    # using the pack() method to place the label in the window
    header_label.pack(expand=TRUE, fill="both", pady=12)

    # creating open button
    open_button = Button(
        buttons_frame,text="Open a File",font=("Calibri", "15"),width=20,bg="white",fg="blue",relief=GROOVE,
        activebackground="blue",command=openAFile
    )
    # rename button
    rename_button = Button(
        buttons_frame,
        text="Rename a File",font=("Calibri", "15"),width=20,bg="white",fg="blue",relief=GROOVE,
        activebackground="white",command=renameAFile
    )

    # copy button
    copy_button = Button(
        buttons_frame,text="Copy the File",font=("Calibri", "15"),width=20,bg="white",fg="blue",
        relief=GROOVE,activebackground="blue",command=copyAFile
    )

    # delete button
    delete_button = Button(
        buttons_frame,text="Delete a File",font=("Calibri", "15"),width=20,bg="white",fg="blue",
        relief=GROOVE,activebackground="white",command=deleteAFile
    )
   # open folder button
    open_folder_button = Button(
        buttons_frame,text="Open a Folder",font=("Calibri", "15"),width=20,bg="white",fg="Blue",
        relief=GROOVE,activebackground="blue",command=openAFolder
    )

    # delete folder button
    delete_folder_button = Button(
        buttons_frame,text="Delete Folder",font=("Calibri", "15"),width=20,bg="white",fg="blue",relief=GROOVE,
        activebackground="blue",command=deleteAFolder
    )

    # move folder button
    move_folder_button = Button(
        buttons_frame,text="Move the Folder",font=("Calibri", "15"),width=20,bg="white",fg="Blue",relief=GROOVE,
        activebackground="Blue",command=moveAFolder
    )
    # list all files button
    list_button = Button(
        buttons_frame,text="List files in Folder", font=("Calibri", "15"),width=20,bg="white",fg="Blue",relief=GROOVE,
        activebackground="Blue",command=listFilesInFolder
    )
    # create an object of Stringvar class
    fileNameEntered = StringVar()

    # use the pack method to place the buttons
    open_button.pack(pady=9)
    rename_button.pack(pady=9)
    copy_button.pack(pady=9)
    delete_button.pack(pady=9)
    move_folder_button.pack(pady=9)
    open_folder_button.pack(pady=9)
    delete_folder_button.pack(pady=9)
    list_button.pack(pady=10)
    win_root.mainloop()

In the above code, we have defined the main() function which consists of the main window of the file explore where we have defined the title, size, and background of the window. We have defined the header frame, header label, and button frame and specified the font, size, foreground, and background color. We have also defined the buttons provided for each of the file explorer operations and specified the desired function using the command attribute for each of the buttons,

We have created the fileNameEntered object of the StringVar() class and win_root, mainloop() function to run the application of python file explorer.

Output:

Function for creating the main window label and buttons for File explorer

Complete Code of File Explorer in Python using Tkinter:

from tkinter import *  # import all the widgets
import os  #importing the os and shutil module
import shutil
from tkinter import messagebox as mb #import the mesassage box for displaying the messages
from tkinter import filedialog as fd  # imports the filedialog  box

# defining the function to open a file
def openAFile():
    # selecting a file using askopenfilename of filedialog as fd
    files = fd.askopenfilename(
        title="Select a file of any type",filetypes=[("All files", "*.*")]
    )
    os.startfile(os.path.abspath(files))


# function to copy a file
def copyAFile():
    # using the filedialog's askopenfilename() method to select the file
    copythefile = fd.askopenfilename(
        title="Select a file to copy",filetypes=[("All files", "*.*")]
    )
    # use the filedialog's askdirectory() method for selecting the directory
    dirToPaste = fd.askdirectory(title="Select the folder to paste the file")
    try:
        shutil.copy(copythefile, dirToPaste)
        mb.showinfo(title="File copied!",message="The file has been copied to the destination."
        )
    except:
        mb.showerror(title="Error!",message="File is unable to copy . Please try again!"
        )

# function to delete a file
def deleteAFile():
    # selecting the file using the filedialog's askopenfilename() method
    files = fd.askopenfilename(
        title="Choose a file to delete",filetypes=[("All files", "*.*")]
    )
    # delete the file using the remove() method
    os.remove(os.path.abspath(files))
    mb.showinfo(title="File deleted!", message="The selected file has been deleted.")


# function to rename a file
def renameAFile():
    rename_win = Toplevel(win_root)
    rename_win.title("Rename File")
    rename_win.geometry("300x100+300+250")
    rename_win.resizable(0, 0)
    rename_win.configure(bg="#F6EAD7")

    # create a lebel
    rename_label = Label(
        rename_win,text="Enter the file name:",font=("Calibri", "8"),bg="white",fg="blue"
    )
    # placing the label on the window
    rename_label.pack(pady=4)
    rename_field = Entry(rename_win,width=26,textvariable=fileNameEntered,relief=GROOVE,
        font=("Calibri", "10"),bg="white",fg="blue"
    )
    # placing the entry field on the window
    rename_field.pack(pady=4, padx=4)

    # creating a button
    submitButton = Button(
        rename_win,text="Submit",command=NameSubmit,width=14,relief=GROOVE,font=("Calibri", "9"),
        bg="white",fg="blue",activebackground="#709218",activeforeground="#FFFFFF"
    )
    submitButton.pack(pady=2)


# defining a function get the file path
def showFilePath():
    files = fd.askopenfilename(title="Select the file to rename", filetypes=[("All files", "*.*")])
    return files


# defining a function that will be called when submit button is clicked
def NameSubmit():
    renameName = fileNameEntered.get()
    # setting the entry field to empty string
    fileNameEntered.set("")
    fileName = showFilePath()
    # creating a new file name for the file
    newFileName = os.path.join(os.path.dirname(fileName), renameName + os.path.splitext(fileName)[1])
    os.rename(fileName, newFileName)
    mb.showinfo(title="File Renamed!", message="The selected file has been renamed.")


# defining a function to open a folder
def openAFolder():
    # using the filedialog's askdirectory() method to select the folder
    folder1 = fd.askdirectory(title="Select Folder to open")
    os.startfile(folder1)


# defining a function to delete the folder
def deleteAFolder():
    folderToDelete = fd.askdirectory(title='Select Folder to delete')
    os.rmdir(folderToDelete)
    mb.showinfo("Folder Deleted!", "The selected folder has been deleted!")


# defining a function to move the folder
def moveAFolder():
    folderToMove = fd.askdirectory(title='Select the folder you want to move')
    mb.showinfo(message='Folder has been selected to move. Now, select the desired destination.')
    des = fd.askdirectory(title='Destination')
    try:
        # using the move() method of the shutil module to move the folder to the requested location
        shutil.move(folderToMove, des)
        mb.showinfo("Folder moved!", 'The selected folder has been moved to the desired Location')
    except:
        mb.showerror('Error!', 'The Folder cannot be moved. Make sure that the destination exists')


#list all files in a folder
def listFilesInFolder():
    i = 0
    # using the askdirectory() method to select the folder
    folder1= fd.askdirectory(title="Select the Folder")
    files = os.listdir(os.path.abspath(folder1))
    listFilesWindow = Toplevel(win_root)
    # specifying the title of the pop-up window
    listFilesWindow.title(f'Files in {folder1}')
    listFilesWindow.geometry("300x500+300+200")
    listFilesWindow.resizable(0, 0)
    listFilesWindow.configure(bg="white")

    # creating a list box
    the_listbox = Listbox(
        listFilesWindow,selectbackground="#F24FBF",font=("Calibri", "10"),background="white"
    )
    the_listbox.place(relx=0, rely=0, relheight=1, relwidth=1)

    # creating a scroll bar
    the_scrollbar = Scrollbar(
        the_listbox,orient=VERTICAL,command=the_listbox.yview
    )
    the_scrollbar.pack(side=RIGHT, fill=Y)
    # setting the yscrollcommand parameter of the listbox's config() method
    the_listbox.config(yscrollcommand=the_scrollbar.set)

    # iterating through the files in the folder
    while i < len(files):
        # using the insert() method to insert the file details in the list box
        the_listbox.insert(END, "[" + str(i + 1) + "] " + files[i])
        i += 1
    the_listbox.insert(END, "")
    the_listbox.insert(END, "Total Files: " + str(len(files)))


if __name__ == "__main__":
    # creating an object of the Tk() class
    win_root = Tk()
    win_root.title("File Explorer")
    win_root.geometry("400x600+650+250")
    win_root.resizable(0, 0)
    win_root.configure(bg="white")

    # creating the frames using the Frame()
    header_frame = Frame(win_root, bg="#D8E9E6")
    buttons_frame = Frame(win_root, bg="skyblue")

    # using the pack() method to place the frames in the window
    header_frame.pack(fill="both")
    buttons_frame.pack(expand=TRUE, fill="both")

    # creating a label using the Label() widget
    header_label = Label(
        header_frame,text="File Explorer",font=("Calibri", "16"),bg="white",fg="blue"
    )

    # using the pack() method to place the label in the window
    header_label.pack(expand=TRUE, fill="both", pady=12)

    # creating open button
    open_button = Button(
        buttons_frame,text="Open a File",font=("Calibri", "15"),width=20,bg="white",fg="blue",relief=GROOVE,
        activebackground="blue",command=openAFile
    )
    # rename button
    rename_button = Button(
        buttons_frame,
        text="Rename a File",font=("Calibri", "15"),width=20,bg="white",fg="blue",relief=GROOVE,
        activebackground="white",command=renameAFile
    )

    # copy button
    copy_button = Button(
        buttons_frame,text="Copy the File",font=("Calibri", "15"),width=20,bg="white",fg="blue",
        relief=GROOVE,activebackground="blue",command=copyAFile
    )

    # delete button
    delete_button = Button(
        buttons_frame,text="Delete a File",font=("Calibri", "15"),width=20,bg="white",fg="blue",
        relief=GROOVE,activebackground="white",command=deleteAFile
    )
   # open folder button
    open_folder_button = Button(
        buttons_frame,text="Open a Folder",font=("Calibri", "15"),width=20,bg="white",fg="Blue",
        relief=GROOVE,activebackground="blue",command=openAFolder
    )

    # delete folder button
    delete_folder_button = Button(
        buttons_frame,text="Delete Folder",font=("Calibri", "15"),width=20,bg="white",fg="blue",relief=GROOVE,
        activebackground="blue",command=deleteAFolder
    )

    # move folder button
    move_folder_button = Button(
        buttons_frame,text="Move the Folder",font=("Calibri", "15"),width=20,bg="white",fg="Blue",relief=GROOVE,
        activebackground="Blue",command=moveAFolder
    )
    # list all files button
    list_button = Button(
        buttons_frame,text="List files in Folder",font=("Calibri", "15"),width=20,bg="white",fg="Blue",relief=GROOVE,
        activebackground="Blue",command=listFilesInFolder
    )
    # create an object of Stringvar class
    fileNameEntered = StringVar()

    # use the pack method to place the buttons
    open_button.pack(pady=9)
    rename_button.pack(pady=9)
    copy_button.pack(pady=9)
    delete_button.pack(pady=9)
    move_folder_button.pack(pady=9)
    open_folder_button.pack(pady=9)
    delete_folder_button.pack(pady=9)
    list_button.pack(pady=10)
    win_root.mainloop()

Hope you find this article helpful. For more articles on python keep visiting our website.

Thank you for reading this article on Python file explorer.


Also Read:

Share:

Author: pranjal dev