Python GUI application to copy files one location to another location

3k views Asked by At

I'm new to python but I have to create a simple GUI application to copy files. This is what I tried.

from Tkinter import *
from  tkFileDialog import askopenfilenames
import shutil,os,glob

def callback():
    src = askopenfilenames()
    des = "C:\Users\Ravi\Desktop\des"
    sourceFiles = os.listdir(src)

    try:
        for fileName in sourceFiles:
            fullName = os.path.join(src, fileName)
            if (os.path.isfile(fullName)):
                shutil.copy(fullName, des)

    except Exception, e:
        print("Error %s" %e)

errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()

When I run this code and trying to copy 1.txt file which is in src, I got following error .

The directory name is invalid: u'C:/Users/Ravi/Desktop/1.txt\\*.*'

I tried this code also to copy files, but it gives no result.

for files in glob.iglob(os.path.join(src, '*.*')):
        shutil.copy(files, des)
        print("copied")

I have no idea, how to configure this application. What I just need is, when I click a "File Open" button and select files and copy selected files in to the destination (des) which I have hard coded(C:\Users\Ravi\Desktop\des). Please help me to correct that code or find another solution for that matter.

2

There are 2 answers

1
Priyanka On

Use below code for Python3. It is working fine.

import shutil,os

def callback():
  src = askopenfilename()

  des = 'C://Users//priyanka.rani//.spyder-py3'
  shutil.copy(src, des)


errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)# calling function to add in Tkinter GUI
mainloop()
1
SiHa On

A full traceback would be useful, but I think your problem is this line:

sourceFiles = os.listdir(src)

src is set to C:/Users/Ravi/Desktop/1.txt (a file, not a directory) by the tkinter dialog and you're trying to do a directory listing of it:

C:/Users/Ravi/Desktop/1.txt\\*.*

Edit: You're also going to have problems with the following block, I think. You seem to be trying to concatenate two filenames together here:

for fileName in sourceFiles:
    fullName = os.path.join(src, fileName)