Move file from folder to folder with python

In this article we will create a python application which will then help us to move a file from one directory to another. Here are the main modules or ingredients we need for our program.

1) tkinter – for creating ui
2) tkinter.filedialog – for opening file and folder
3) os – for removing old file once it has been moved to a new folder

First of all, lets import those modules we need.

import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
import tkinter.font as Font
from shutil import copyfile
import os
from os.path import basename

Next create the user interface with tkinter module

win = tk.Tk()
win.title("Copy File")

# The callback function of the button
def clickMe():
   # code will goes here

# Adding a Button
action = ttk.Button(win, text="Move File", command=clickMe)  # click on the button to open file chooser
action.grid(column=0, row=0)

win.mainloop()  # run the main loop

The user interface of the application is very simple, just a button and when it gets clicked the file and folder chooser will open up and the file moving process will take place.

# The callback function of the button
def clickMe():

    filename = askopenfilename(title="Select text file")
    foldername = askdirectory(title="Select folder")
    copyfile( filename, os.path.join(foldername, basename(filename)))
Click on the button
Click on the button

Enter above code into the clickMe function which will move the file to a new location.

Next run the application, clicking on the button as shown below then pick a file and the new location to move the file to and that is it!

Leave a Reply

Be the First to Comment!

Notify of