2015-05-04 76 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