复制文件夹和子文件夹,但仅复制子文件夹中具有 python 的第一个文件
Copy folders and subfolders, but only first files in subfolders with python
我有一个包含文件夹、子文件夹、子子文件夹的文件结构 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
我不知道你是否可以自定义那么多的复制树,但是使用 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)
我有一个包含文件夹、子文件夹、子子文件夹的文件结构 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
我不知道你是否可以自定义那么多的复制树,但是使用 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)