Coding-python-复制当前目录下的所有文件到指定的目标目录

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import os
import shutil

def copy_files_to_directory(source_dir=None, target_dir=None):
"""
复制当前目录下的所有文件到指定的目标目录。

:param source_dir: 源目录,默认为当前工作目录。
:param target_dir: 目标目录,如果目录不存在则自动创建。
"""
if source_dir is None:
source_dir = os.getcwd() # 当前工作目录
if target_dir is None:
raise ValueError("Target directory must be specified.")

# 确保目标目录存在
if not os.path.exists(target_dir):
os.makedirs(target_dir)

# 遍历源目录中的所有文件
for filename in os.listdir(source_dir):
full_source_path = os.path.join(source_dir, filename)
full_target_path = os.path.join(target_dir, filename)

# 只复制文件,忽略子目录
if os.path.isfile(full_source_path):
shutil.copy2(full_source_path, full_target_path)
print(f"Copied {filename} to {target_dir}")

# 使用函数
source_directory = "datasets/result/valid/images"
target_directory = "datasets/clothes/valid/images" # 目标目录

# # 使用函数
# source_directory = "train/labels"
# target_directory = "datasets/clothes/train/labels" # 目标目录
copy_files_to_directory(source_directory, target_directory)
print("final")