2015-06-08 39 views
0

我是新來的python,但我必須創建一個簡單的GUI應用程序來複制文件。這是我試過的。Python GUI應用程序將文件的一個位置複製到另一個位置

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() 

當我運行此代碼並試圖複製src中的1.txt文件時,出現以下錯誤。

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

我試過這個代碼也複製文件,但它沒有給出任何結果。

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

我不知道如何配置此應用程序。我只需要點擊「文件打開」按鈕並選擇文件並將選中的文件複製到我已硬編碼的目標(des)(C:\Users\Ravi\Desktop\des)。請幫助我糾正該代碼或找到另一個解決方案。

+1

我建議使用shutil more來處理路徑和文件。你需要看看os.path()https://docs.python.org/2/library/os.path.html如果你使用python 3(3.4),我會說使用shltil docs https的pathlib – lxx

+0

鏈接://docs.python.org/2/library/shutil.html – lxx

+0

如果您知道文件名,則不需要使用通配符,如*。*。 – lxx

回答

1

一個完整的追溯將是有益的,但我覺得你的問題是這一行:

sourceFiles = os.listdir(src)

src設置爲C:/Users/Ravi/Desktop/1.txt(文件,目錄)由Tkinter的對話框,您正在嘗試做的是一個目錄列表:

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

編輯:你也將有問題我認爲以下塊。你似乎試圖在這裏連接兩個文件名:

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

是的,我單獨嘗試了複製部分,它工作的很好,但我不知道如何將它插入到gui中。 – RYJ

相關問題