Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 复制具有不同名称的文件夹中的文件_Python - Fatal编程技术网

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

Python 复制具有不同名称的文件夹中的文件,python,Python,我需要从名为shape的文件夹中复制文件,但此文件夹位于另一个具有不同名称的文件夹中 例如,我有1000个文件夹,所有文件夹都有不同的名称,但每个文件夹中都有一个名为shape的文件夹,我想用python编写一个脚本,自动复制该文件夹中shape文件夹的所有文件,该文件夹更改名称并将其粘贴到另一个始终相同的目录中 txs提前。编辑:受@fernand0评论启发,一种更简单的方法是运行: import subprocess root_dir = "/Users/krekto/lots_of_fo

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

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

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))

您需要用Python来完成吗?仅仅使用shell命令不是更容易吗?。类似mv*/shape/*dest/的东西可以吗?os.rename、copyfilesrc、dst、glob os.remove。接下来在@fernand0上,为了“Pythonize”他说的话,只需运行p=subprocess.Popenmv*/shape/*dest/.split,cwd=my/source/directory