我想将文件从复杂的目录结构移动到一个位置。例如,我有这个深层次的:
foo/
foo2/
1.jpg
2.jpg
...
我希望它是:
1.jpg
2.jpg
...
我当前的解决方案:
def move(destination):
for_removal = os.path.join(destination, '\\')
is_in_parent = lambda x: x.find(for_removal) > -1
with directory(destination):
files_to_move = filter(is_in_parent,
glob_recursive(path='.'))
for file in files_to_move:
shutil.move(file, destination)
定义:directory
和glob_recursive
。请注意,我的代码仅将文件移动到其公共父目录,而不是任意目的地。
如何将所有文件从复杂的层次结构简洁而优雅地移动到单个位置?
在目录中递归运行,移动文件并启动move
目录:
import shutil
import os
def move(destination, depth=None):
if not depth:
depth = []
for file_or_dir in os.listdir(os.path.join([destination] + depth, os.sep)):
if os.path.isfile(file_or_dir):
shutil.move(file_or_dir, destination)
else:
move(destination, os.path.join(depth + [file_or_dir], os.sep))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句