我有 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'
}
如何使用 map 的项目作为 shutil.move() 函数的参数?我尝试了几种方法都没有成功。
请您参考如下方法:
关于:
for frm,to in files.items():
shutil.move(frm,to)
您只需遍历字典的 (key,value) 元组,然后调用 shutil.move对这些起作用。
我看到的唯一问题是您可能需要先构建目录:否则移动对象可能会失败。您可以通过首先检测 os.path.dirname 来做到这一点,检测目录是否存在,如果不存在则创建这样的目录:
#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)
