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



我在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)

您只需遍历字典的(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)

最新更新