Python 3.x 根据Python中的名称将文件从单独的子目录移动到另一个子目录
给定目录Python 3.x 根据Python中的名称将文件从单独的子目录移动到另一个子目录,python-3.x,operating-system,shutil,Python 3.x,Operating System,Shutil,给定目录/及其子目录('project1,project2,project3,…')和文件结构如下: ├── project1 │ ├── file1 │ ├── file2 │ ├── process │ │ └── f1 │ │ ├── pic1.png │ │ └── pic2.jpg │ ├── progress │ │ └── f2 │ │ ├── 623.jpg │ │ └── pic23
/
及其子目录('project1,project2,project3,…')
和文件结构如下:
├── project1
│ ├── file1
│ ├── file2
│ ├── process
│ │ └── f1
│ │ ├── pic1.png
│ │ └── pic2.jpg
│ ├── progress
│ │ └── f2
│ │ ├── 623.jpg
│ │ └── pic2323.png
│ └── session
│ └── f3
│ ├── 5632116.jpg
│ └── 72163.png
└── project2
├── file1
├── file2
├── process
│ └── f1
│ ├── pic1.png
│ └── pic2.jpg
├── progress
│ └── f2
│ ├── 623.jpg
│ └── pic2323.png
└── session
└── f3
├── 5632116.jpg
└── 72163.png
对于每个项目
文件夹,我需要将图片从进程
移动到空文件1
,从进度
和会话
移动到空文件2
预期结果如下:
|── project1
| ├── file1
| │ ├── pic1.png
| │ └── pic2.jpg
| |── file2
| ├── 623.jpg
| └── pic2323.png
| ├── 5632116.jpg
| └── 72163.png
└── project2
├── file1
│ ├── pic1.png
│ └── pic2.jpg
|── file2
├── 623.jpg
└── pic2323.png
├── 5632116.jpg
└── 72163.png
我的试用代码有效,但我认为不够简洁,欢迎改进:
base_dir = './'
src_dst_map = {
'session': 'files1',
'process': 'files2',
'progress': 'files2'
}
for child in os.listdir(base_dir):
# print(child)
child_path = os.path.join(base_dir, child)
# print(child_path)
# src_path = os.path.join(child_path, 'session')
# print(src_path)
for src, dst in src_dst_map.items():
# print(src)
src_path = os.path.join(child_path, src)
dst_path = os.path.join(child_path, dst)
print(src_path)
print(dst_path)
for root, dirs, files in os.walk(src_path):
# print(root)
for file in files:
# print(file)
srce_path = os.path.join(root, file)
print(srce_path)
shutil.move(srce_path, dst_path)
shutil.rmtree(src_path, ignore_errors = True)
老实说,这已经相当简洁了,而且它确实起到了作用,所以我不会太费心去修改它。您的代码在10行中运行(加上字典和基本路径的设置) 关于复制的图像,您可以检查
dst_path
中是否存在文件
,如果存在,请向复制的文件添加前缀(或后缀)
在下面的示例中,根据源添加前缀,直到找到唯一的文件名。如果在一个子文件夹中有同一文件的多个副本,则此操作也会捕获。你可以根据你的具体需求来改变,但它应该给你一个大致的想法
...
for root, dirs, files in os.walk(src_path):
for file in files:
srce_path = os.path.join(root, file)
while os.path.isfile(os.path.join(dst_path, file)):
file = '_'.join([src, file])
shutil.move(srce_path, os.path.join(dst_path, file))
我选择了前缀,因为这更容易实现。必须在文件名和文件结尾之间添加后缀,这需要一些额外的代码。您到底想改进什么?它应该更通用,或者更容易阅读,或者您正在寻找减少代码行的方法吗?如果可能的话,要减少代码行,我认为我的代码不够简洁。如果我还想将重复的名称图像移动到
dst_path
,将它们都保存,我该怎么做?有什么想法吗?