use*_*249 1 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'
}
Run Code Online (Sandbox Code Playgroud)
如何使用地图项作为shutil.move()函数的参数?我尝试了几种方法却没有成功.
关于什么:
for frm,to in files.items():
shutil.move(frm,to)
Run Code Online (Sandbox Code Playgroud)
您只需遍历(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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
50 次 |
| 最近记录: |