继续How can i move files from one directory to another?我尝试使用此代码将所有jpg文件从文件夹r“C:\ Project \ layers”移动到文件夹r“C:\ Project \ layers \ new”,但是我得到了错误:
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 :(得分:3)
您需要加入文件的路径:
os.path.join(source,f)
layers
是一个目录,因此...layers+filename
不存在但...layers\filename
不存在。你正在连接这两个字符串,你最后可以使用source = r"C:\Project\layers\"
反斜杠,但最好使用join。