我需要从名为 shape 的文件夹中复制文件,但该文件夹位于另一个名称不同的文件夹中。
例如,我有 1000 个文件夹,所有文件夹都有不同的名称,但在每个文件夹中,我都有一个名为 shape 的文件夹,我想在 python 中创建一个脚本,该脚本自动复制该文件夹内的该形状文件夹的所有文件,该文件夹更改名称并将其粘贴到另一个始终相同的目录中。
提前txs。
编辑:受@fernand0 评论启发,一种更简单的方法是运行:
import subprocess
root_dir = "/Users/krekto/lots_of_folders/"
destination = "/Users/krekto/my_destination/"
cmd = "mv */shape/* {}".format(destination)
p = subprocess.call(cmd.split(),cwd=root_dir,shell=True)
我无法对此进行测试,但它应该可以满足您的需求。
import os
import shutil
# Set up directory you want to copy from and to
root_dir = "/Users/krekto/lots_of_folders/"
destination = "/Users/krekto/my_destination/"
# Get the list of all directories in root_dir
for root, dirs, files in os.walk(root_dir, topdown=True):
dir_list = dirs
break
# Iterate over this list and see if 'shape/' exists
for dir in dir_list:
sub_dir = os.listdir(dir) # List of all contents in dir
# Iterate over contents and see if 'shape/' is present
for d in sub_dir:
# If so, copy all files and directories from it
if d.lower() == 'shape':
shape_dir = os.path.join(root_dir,dir,d)
for f in os.list(shape_dir):
shutil.copyfile(os.path.join(shape_dir,f),os.path.join(destination, f))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句