2015-05-04 75 views
1

Continusly到How can i move files from one directory to another?我嘗試所有的JPG文件從文件夾中R「C:\項目\層」移動到文件夾R「C:\項目\圖層\新」與此代碼,但我得到的連接錯誤:移動文件

import shutil, os 
source = r"C:\Project\layers" 
destination = r"C:\Project\layers\new" 
if not os.path.exists(destination): 
    os.makedirs(destination)    
for f in os.listdir(source): 
    if f.endswith(".jpg"): 
     shutil.move(source + f, destination) 

錯誤:

Traceback (most recent call last): 
    File "C:\Users\yaron.KAYAMOT\Desktop\python.py", line 8, in <module> 
    shutil.move(source + f, destination) # add source dir to filename 
    File "C:\Python27\ArcGISx6410.3\lib\shutil.py", line 302, in move 
    copy2(src, real_dst) 
    File "C:\Python27\ArcGISx6410.3\lib\shutil.py", line 130, in copy2 
    copyfile(src, dst) 
    File "C:\Python27\ArcGISx6410.3\lib\shutil.py", line 82, in copyfile 
    with open(src, 'rb') as fsrc: 
IOError: [Errno 2] No such file or directory: 'C:\\Project\\layerslogo1.jpg' 
>>> 
+0

它不添加目錄名(層)和文件名(logo1.jpg)之間的斜線,所以它在尋找一個叫做'layerslogo1.jpg'在'Project'目錄下的文件。你需要在'source + f'中添加斜槓,或者更好的使用'os.path.join(source,f)'。 – alexwlchan

+0

你應該學會閱讀錯誤信息:「沒有這樣的文件或目錄:'C:\\ Project \\ layerslogo1.jpg'」。是否存在'C:\\ Project \\ layerslogo1.jpg'?不,它不。那麼你的下一個問題就是爲什麼你的程序試圖使用這個路徑而不是正確的'C:\\ Project \\ layers \ logo1.jpg'。 – poke

+0

戳,你是什麼意思? – newGIS

回答

3

你需要加入的文件路徑:

os.path.join(source,f) 

layers是廣告irectory so ...layers+filename不存在,但...layers\filename呢。您將兩個字符串連接在一起,您可以在末尾使用帶反斜槓的source = r"C:\Project\layers\",但可能最好使用連接。

+0

GET恩壓痕錯誤 – newGIS

+0

@newGIS,這無關使用path.join,所有你需要做的就是更換'shutil.move(來源+ F,目的地)'和'shutil.move(os.path.join (源,f)中,目的地)' –

+0

GET烯錯誤:IO錯誤:[錯誤2]沒有這樣的文件或目錄: 'C:\\項目\\ layerslogo1.jpg' – newGIS