[英]How to copy 700 files + 80 files into two different directory from same source, using loop in Python?
我想从源文件夹 Z 复制文件夹 Train 中的 700 个文件和文件夹 Test 中的 80 个文件( Z 有 780 个文件)。 你能用循环解决这些问题吗,在此先感谢
我尝试使用此代码:
sourceImage = "D:/DeveloperWorld/a-zDatasets"
train_folder = "D:/CheckFolder/train"
test_folder = "D:/CheckFolder/test"
src_files = os.listdir(sourceImage)
length = len(src_files)
for f in src_files:
full_file_name = os.path.join(sourceImage, f)
for i in range(0,700):
shutil.copy(full_file_name, train_folder)
break
for i in range(700,780):
shutil.copy(full_file_name, test_folder)
break
这是 shell 命令
cp -r path/to/A/* path/to/Z/
这表示
递归复制源A
所有内容(注意*
)到目标Z
您可以使用os在您的 python 代码中执行 shell 命令
import os
os.system("cp -r path/to/A/* path/to/Z/")
os.system("cp -r path/to/B/* path/to/Z/")
似乎您正在尝试使用循环移动所有这些 780 个文件。 问题是当您使用嵌套循环时,您可能因此循环了数十万次。
似乎您已经从src_files
变量中获取了文件列表。 尝试这个。
sourceImage = "D:/DeveloperWorld/a-zDatasets"
train_folder = "D:/CheckFolder/train"
test_folder = "D:/CheckFolder/test"
src_files = os.listdir(sourceImage)
length = len(src_files)
for idx, f in enumerate(src_files):
full_file_name = os.path.join(sourceImage, f)
if idx <= 700:
shutil.copy(full_file_name, train_folder)
else:
shutil.copy(full_file_name, test_folder)
枚举 function 为您提供索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.