2017-02-17 53 views
0

我需要到一個文件夾中的第一個文件移動到我的當前目錄:移動從文件夾中第一個文件到當前目錄

import os 
import shutil 

shutil.move(os.listdir('path to folder')[-1], os.getcwd()) 

我得到的錯誤:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'name of the file I want to move' 

有人能指出什麼請問我做錯了?

謝謝!

回答

1

好吧,當我不得不移動文件我寫了這樣的事情:

for file in os.listdir(self.dlPth):  
    newfile = os.path.join(self.destPth, "name-of-new-file") 
    shutil.move(os.path.join(self.dlPth,file), newfile) 

destPth是目標路徑和dlPth是一個在我的文件被下載。

你可以給你使用的路徑嗎?我的意思是你寫代碼的確切方式?


編輯

dl = os.path.join(os.getenv('USERPROFILE'), 'Downloads') 
shutil.move(os.path.join(dl, os.listdir(dl)[0]), (dl+"\\test\\")) 

listdir同時[指數]只會返回一個文件名,不是路徑。這就是爲什麼它找不到想要的文件

+0

:'shutil.move(os.listdir('E:/ PyCharm/Translations/Testing/French_start')[ - 1],os.getcwd())' –

+0

Try寫成「E:\\ PyCharm \\ Translations ...」。而且,如果你想要第一個文件,爲什麼你使用[-1]而不是[0]?通過調用[-1],您將得到列表的最後一項 – Alastard

+0

我試過了,代碼找到了文件名並將其返回給錯誤消息。 ([1]只是對最後一個文件的測試,結果相同)。 –

相關問題