Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.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_Copy_Shutil_File Structure - Fatal编程技术网

使用python复制文件夹和子文件夹,但仅复制子文件夹中的第一个文件

使用python复制文件夹和子文件夹,但仅复制子文件夹中的第一个文件,python,copy,shutil,file-structure,Python,Copy,Shutil,File Structure,我有一个包含文件夹、子文件夹、子文件夹a.s.o.的文件结构。只有最后一个子文件夹包含文件。我希望复制文件结构,而不是复制所有文件,而是仅复制每个子文件夹中的第一个文件(或仅一个文件)。我注意到shutil.copytree(src,dst)可以做类似的事情,但我不知道如何限制它只复制子文件夹中的第一个文件。感谢您对如何完成此任务的建议 我的文件结构: folder1 subfolder11 subsubfolder111 file1 file2

我有一个包含文件夹、子文件夹、子文件夹a.s.o.的文件结构。只有最后一个子文件夹包含文件。我希望复制文件结构,而不是复制所有文件,而是仅复制每个子文件夹中的第一个文件(或仅一个文件)。我注意到
shutil.copytree(src,dst)
可以做类似的事情,但我不知道如何限制它只复制子文件夹中的第一个文件。感谢您对如何完成此任务的建议

我的文件结构:

folder1
  subfolder11
    subsubfolder111
      file1
      file2
      file3...
folder2
  sulfolder21
    file1
    file2
    file3...
folder1
  subfolder11
    subsubfolder111
      file1
folder2
  sulfolder21
    file1
所需结构:

folder1
  subfolder11
    subsubfolder111
      file1
      file2
      file3...
folder2
  sulfolder21
    file1
    file2
    file3...
folder1
  subfolder11
    subsubfolder111
      file1
folder2
  sulfolder21
    file1

我不知道您是否可以自定义这么多的copytree,但使用os.walk和解析文件夹,您可以做到这一点,下面是一个示例:

import os
import shutil

p1 = r"C:\src_dir"
p2 = r"C:\target_dir"

for path, folders, files in os.walk(p1):

    if not files: continue

    src = os.path.join(path, files[0])
    dst_path = path.replace(p1, '') + os.sep
    dst_folder = p2 + dst_path

    # create the target dir if doesn't exist
    if not os.path.exists(dst_folder):
        os.makedirs(dst_folder)

    # create dst file with only the first file
    dst = p2 + dst_path + files[0]

    # copy the file
    shutil.copy2(src, dst)

根据GuillaumeJ的回答,可以将复制概括为N个文件:

# limit of files to copy
N=3

for path, folders, files in os.walk(p1):

    # you might want to sort files first before executing the below
    for file_ in files[:N]:
    # if not files: continue

        src = os.path.join(path, file_)
        dst_path = path.replace(p1, '') + os.sep
        dst_folder = p2 + dst_path

        # create the target dir if doesn't exist
        if not os.path.exists(dst_folder):
            os.makedirs(dst_folder)

        # create dst file with only the first file
        dst = p2 + dst_path + file_

        # copy the file
        shutil.copy2(src, dst)

使用递归函数怎么样。你拿一个文件夹;若它是一个文件,你们复制它并退出递归,若它是一个目录,你们对它重复这个过程。