2017-05-11 53 views
1

我編寫了以下代碼來識別和組織gif和圖像文件。 cdir指的是程序應該組織的目錄。當它被執行時,它應該在同一個目錄中創建文件夾'Gifs'和'Images'。嘗試使用Shutil Python模塊移動文件時出現FileNotFound錯誤

import shutil, os 

gifext = ['.gif', 'gifv'] 
picext = ['.png', '.jpg'] 

for file in files: 
    if file.endswith(tuple(gifext)): 
     if not os.path.exists(cdir+'\Gifs'): 
      os.makedirs(cdir + '\Gifs') 
     shutil.move(cdir + file, cdir + '\Gifs') 

    elif file.endswith(tuple(picext)): 
     if not os.path.exists(cdir+'\Images'): 
      os.makedirs(cdir + '\Images') 
     shutil.move(cdir + file, cdir + '\Images') 

該目錄包含的文件:FIRST.gif,SECOND.gif和THIRD.jpg

,但我得到了以下錯誤:

File "test.py", line 16 
    shutil.move(cdir + file, cdir + '\Gifs') 
    File "C:\Users\stavr\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 552, in move 
    copy_function(src, real_dst) 
    File "C:\Users\stavr\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 251, in copy2 
    copyfile(src, dst, follow_symlinks=follow_symlinks) 
    File "C:\Users\stavr\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 114, in copyfile 
    with open(src, 'rb') as fsrc: 
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\stavr\\Desktop\\testFIRST.gif' 
+0

這個問題不值得讚賞。是的,這個問題對於經驗豐富的Pythonistas來說有點微不足道。但是*問題*僅僅是示例性的**:清晰的問題陳述,預期的結果/實際結果,完整的,自包含的和可執行的代碼,完整的回溯。 –

+0

感謝您的回覆! – Smich

回答

2

files只包含文件的名稱在一個目錄中。 cdir沒有在最後一個反斜槓,因此,當您連接cdirfiles元素你會得到潛在無效路徑:

"C:\stuff\my\path" + "file_name.png" 
# equals 
"C:\stuff\my\pathfile_name.png" 

後者顯然不是你想要的,所以你應該補充一點,以某種方式反衝至cdir,可能是這樣的:

if not cdir.endswith("\\"): 
    cdir += "\\" 
+1

'cdir.endswith(os.sep):'更好,或者建議使用'os.path.join'和原始字符串。 –

1

您的文件路徑不正確。有一個路徑分隔符丟失。

shutil.move(os.path.join(cdir, file), os.path.join(cdir, 'Gifs')) 
+1

而不是手動連接路徑,應該使用['os.path.join'](https://docs.python.org/3/library/os.path.html#os.path.join)。這首先會防止這種錯誤,並且還會導致可移植的代碼。 –

0

繼錯誤報告有一個「\」在目錄中的「測試」 UND文件「FIRST.gif」之間的路徑丟失:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\Users\\stavr\\Desktop\\testFIRST.gif' 

您可通過添加解決這個「 \」當你把這樣的路徑:

Enter path to the directory: C:\Users\stavr\Desktop\test\ 

OR

取代:

shutil.move(cdir + file, cdir + '\Gifs') 

由:

shutil.move(os.getcwd() + '/' + file, cdir + '\Gifs') 

順便說一句: 我認爲這裏有一個 「」在「gifv」之前缺失

gifext = ['.gif', 'gifv'] 
相關問題