复制具有不同名称的文件夹中的文件

时间:2017-11-16 18:58:37

标签: python

我需要从名为shape的文件夹中复制文件,但此文件夹位于另一个名称不同的文件夹中。

例如我有1000个文件夹都有不同的名称,但在每个文件夹中都有一个名为shape的文件夹,我想在python中创建一个自动复制该文件夹内该形状文件夹的所有文件的脚本更改名称并将其粘贴到另一个始终相同的目录中。

提前txs。

1 个答案:

答案 0 :(得分:1)

编辑:受@ 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))