在python中移动字典中的引用文件

在python中移动字典中的引用文件,python,dictionary,shutil,Python,Dictionary,Shutil,我有Python字典,其中包括文件的当前路径和所需路径 files = { 'C:\\Users\\a\\A\\A.jpg': 'C:\\Users\\a\\A\\test_a\\A.jpg', 'C:\\Users\\a\\B\\B.jpg': 'C:\\Users\\a\\B\\test_a\\B.jpg', 'C:\\Users\\a\\C\\C.jpg': 'C:\\Users\\a\\test_a\\C.jpg' } 如何使用映射的项作为shutil.move

我有Python字典,其中包括文件的当前路径和所需路径

files = {
    'C:\\Users\\a\\A\\A.jpg': 'C:\\Users\\a\\A\\test_a\\A.jpg',
    'C:\\Users\\a\\B\\B.jpg': 'C:\\Users\\a\\B\\test_a\\B.jpg',
    'C:\\Users\\a\\C\\C.jpg': 'C:\\Users\\a\\test_a\\C.jpg'
}
如何使用映射的项作为shutil.move函数的参数?我尝试了几种方法都没有成功。

那么:

for frm,to in files.items():
    shutil.move(frm,to)
您只需迭代字典的键、值元组,并调用这些元组上的函数

我看到的唯一问题是,您可能需要首先构造目录:否则,移动对象可能会失败。您可以首先检测,检测目录是否存在,如果不存在,则创建这样的目录:

#only if you are not sure the directory exists
for frm,to in files.items():
    directory = os.path.dirname(to)
    os.makedirs(directory,exist_ok=True) #create a directory if it does not exists
    shutil.move(frm,to)
那么:

for frm,to in files.items():
    shutil.move(frm,to)
您只需迭代字典的键、值元组,并调用这些元组上的函数

我看到的唯一问题是,您可能需要首先构造目录:否则,移动对象可能会失败。您可以首先检测,检测目录是否存在,如果不存在,则创建这样的目录:

#only if you are not sure the directory exists
for frm,to in files.items():
    directory = os.path.dirname(to)
    os.makedirs(directory,exist_ok=True) #create a directory if it does not exists
    shutil.move(frm,to)

你能告诉我们你试过什么吗?对于键值对,您期望发生什么?对于源,文件中的dest.items:shutil.movesource,dest是否涵盖它?您能告诉我们您尝试了什么吗?对于键值对,您期望发生什么?对于源,是否在文件中删除。items:shutil.movesource,dest是否覆盖它?