Friday, December 14, 2018

codingdirectional: Move files from one folder to another folder with python

After I have finished writing the python program which will remove the duplicate files in another folder, the first part of this tkinter’s project has come to an end and the second part will follow. Just in case you miss out the first part of the project completely then make sure to read the previous articles about it, you can also download the remove duplicate application bundle for windows os through this link then either start the application file or run it’s main file on the windows command prompt by following the instructions on this previous article.

With that we are now ready to move on to the second part of the project which is to move a file or files from one folder to another. If you have followed my previous articles then you know that we have created a remove thread to remove all the duplicate files, we will use back the same skeleton of the remove thread to create a thread class which we will call it the copy class which has only one simple mission — move a file or files from one folder to another. First of all lets create the Copy class.

import threading
import os
from shutil import copyfile

class Copy(threading.Thread):

    def __init__(self, massage,  filename, fullfilename,):

        threading.Thread.__init__(self)
        self.massage = massage
        self.src = fullfilename
        self.dst = os.path.join(self.massage, filename)

    def run(self):

        copyfile(self.src, self.dst)
        os.remove(self.src)


As you can see from above the copy class is using the same skeleton as the remove class but this time we have simplified the process, the run method of the thread will perform this two tasks 1) Move the old file to the new directory 2) Delete the old file in the old directory.

Next, we will edit the main file by including a copy file method which will be called when the user clicks on the Move button, the user will need to select a file or files from a folder and then select another folder which he wishes to move those files to. The content of the copy file method will mostly be the same as the select file method which we used to select a file or files that we wish to remove their duplicate copies from. Here is the source code for the main file.

from tkinter import *
from tkinter import filedialog
from Remove import Remove
import os
from tkinter import messagebox
import webbrowser
from Copy import Copy

win = Tk() # 1 Create instance
win.title("Multitas") # 2 Add a title
#win.iconbitmap(os.path.abspath('icon.ico'))
win.resizable(0, 0) # 3 Disable resizing the GUI
win.configure(background='black') # 4 change background color
#win.iconbitmap(('icon.ico'))

# 5 Create a label
aLabel = Label(win, text="Select a task", anchor="center", padx=13, pady=10, relief=RAISED)
aLabel.grid(column=0, row=0, sticky=W+E)
aLabel.configure(foreground="white")
aLabel.configure(background="black")
aLabel.configure(wraplength=96)
aLabel.message = ''

# 6 Create a selectFile function to be used by action button
def selectFile():

    fullfilenames = filedialog.askopenfilenames(initialdir="/", title="Select a file") # select multiple files from the hard drive

    if(fullfilenames != ''):

        fullfilenamelist = win.tk.splitlist(fullfilenames)
        directory_path = os.path.dirname(os.path.abspath(fullfilenamelist[0]))

        os.chdir(directory_path)  # change the directory to the selected file directory

        folder = filedialog.askdirectory()  # 7 open a folder then create and start a new remove thread to delete the duplicate file
        folder = folder.replace('/', '\\')  # 8 this is for the windows separator only

        if(folder != '' and folder != os.getcwd()):

            for fullfilename in fullfilenamelist:

                if(fullfilename != ''):
                    filename = fullfilename.split('/')[-1]
                    remove = Remove(folder, filename, fullfilename, directory_path, aLabel)
                    remove.start()
                    remove.join()
                    messagebox.showinfo('Remove the duplicate files', aLabel.message)

        else:
            messagebox.showinfo("Error", "Kindly select one folder and it must be a different one")
            return

    else:
        messagebox.showinfo("Select file", "You need to select a file!")
        return

# 6 Create a copyFile function to move a file from one folder to another
def copyFile():

    fullfilenames = filedialog.askopenfilenames(initialdir="/", title="Select a file") # select multiple files from the hard drive

    if(fullfilenames != ''):

        fullfilenamelist = win.tk.splitlist(fullfilenames)
        directory_path = os.path.dirname(os.path.abspath(fullfilenamelist[0]))

        os.chdir(directory_path)  # change the directory to the selected file directory

        folder = filedialog.askdirectory()  # 7 open a folder then create and start a new Copy thread to move the file from one directory to another one
        folder = folder.replace('/', '\\')  # 8 this is for the windows separator only

        if(folder != '' and folder != os.getcwd()):

            for fullfilename in fullfilenamelist:

                if(fullfilename != ''):
                    filename = fullfilename.split('/')[-1]
                    copy = Copy(folder, filename, fullfilename)
                    copy.start()
                    copy.join()
                    messagebox.showinfo('Move the file ', 'File has been moved to new destination')

        else:
            messagebox.showinfo("Error", "Kindly select one folder and it must be a different one")
            return

    else:
        messagebox.showinfo("Select file", "You need to select a file!")
        return

def openLink(): # start a new link

    webbrowser.open_new("http://codingdirectional.info/2018/12/12/remove-duplicate-files-project-is-ready/")

# 9 Adding a Button

action = Button(text="Remove", command=selectFile)
action.grid(column=0, row=1, sticky=S+W)
action.configure(background='black')
action.configure(foreground='white')

action_move = Button(text="Move", command=copyFile)
action_move.grid(column=0, row=1, sticky=S+E)
action_move.configure(background='black')
action_move.configure(foreground='white')

action_link = Button(text="Manual", command=openLink)
action_link.grid(column=1, row=1, sticky=S+E)
action_link.configure(background='black')
action_link.configure(foreground='white')

win.mainloop()  # 10 start GUI

With that we have finished the second part of the project and is now ready to move on to the third part of the project. But before we move on, we will do some modifications on the arrangement of the buttons in the next chapter which we will create a container to contain more buttons for the future usage.

Again if you are new to this project then don’t forget to download the first part of the project through this link. This application is only for the windows os user but if you are using linux and are familiar with python programming then you should be able to easily modify this program for your own use.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...