做猫狗分类任务,要求数据集划分为训练集(training dataset)和验证集(validation dataset),均包含dogs和cats两个目录,且每个目录下包含与目录名类别相同的RGB图。数据集共25000张照片,其中训练集猫狗照片各10000张,验证集猫狗照片各2500张。但我下载的数据只有一个包含所有猫狗图的文件夹,于是需要遍历所有文件并且移动,代码如下:
import os
import shutil
path = "C:\\Users\\Administrator\\Documents\\Python\\dnnlearn\\dogcat\\dataset"
src_dir = os.path.abspath(path + "\\train")
dst_dir = os.path.abspath(path + "\\dog")
cat_dir = os.path.abspath(path + "\\")
train__dir = os.path.abspath(src_dir + "\\train\\dog")
count = 0
if not os.path.exists(src_dir):#创建文件夹
os.makedirs(src_dir)
#if not os.path.exists(train_cat_dir):
# os.makedirs(train_cat_dir)
if os.path.exists(src_dir):
for root, dirs, files in os.walk(src_dir):
'''
print("root:",root)#文件夹路径
print("dirs:",dirs)#文件夹名称
print("files:",files)#文件名
'''
for file in files:#遍历每一个文件
#filename = os.path.basename(file)#获取文件名
#if count <= 2500:
dog_file = os.path.join(src_dir, file)#拼接得到文件路径
shutil.move(dog_file, dst_dir)#移动文件
#print(count)
Python遍历文件好像是按照深度搜索进行的,有一个如下结构的文件夹:
遍历结果为:
版权声明:本文为weixin_42182906原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。