python从指定文件夹复制部分文件到另一文件夹

尝试使用python对原来的数据集进行了新的组织,原来是想做多分类就使用了多级多病例的组织方式,现在做二分类只需将阳性阴性病例按比例划分至训练集和测试集。
新的组织方式如下:
在这里插入图片描述

定义移动函数remove_file

后来想了想应该叫copy函数的,但是也懒得改了,标注一下继续使用先

函数接收旧的路径和新路径以及要将病例训练集测试集划分的比例


os.listdir(path)

path – 需要列出的目录路径
用于返回指定的文件夹包含的文件或文件夹的名字的列表


shuffle()

lst – 可以是一个列表
shuffle() 方法将序列的所有元素随机排序

shuffle()是不能直接访问的,需要导入 random 模块,然后通过 random 静态对象调用该方法。

import random
random.shuffle (lst )

remove_file()

def remove_file(old_path,new_path,ratio):
    print(old_path)
    print(new_path)
    filelist=os.listdir(old_path)
    shuffle(filelist) #打乱列表,让每次创建新的数据集时用于训练和测试的部分有所区别

阳性病例集

原来的组织方式是一个病例一个文件夹,文件夹名中的病类(大写英文字母)表示其阴性或阳性。

   for file in filelist:
        if file[0]=='A':  # 如'A001'
            src_path=old_path+'\\'+file
            print(src_path)
            src_filelist=os.listdir(src_path)
            print(len(src_filelist)) #查看有文件夹下有几张图片
            point=ratio*len(src_filelist) #要放进训练集的图片数量
            x=0

定义变量point作为一个病例用来训练的图片数量,如一个病例100张图片,ratio=0.7,则使用70张用于训练,30张用于测试。
刚开始学习python,很多地方不熟悉,所以乱拼凑出了这么冗长的代码,要好好掌握语言!

for src_file in src_filelist:
                if x<point:
                    src=os.path.join(src_path,src_file)
                    print(src_path)
                    dst_path=new_path+'\\'+'train'
                    print(dst_path)
                    dst=os.path.join(dst_path)
                    print(src)
                    shutil.copy(src,dst)
                    x+=1
                else:
                    src=os.path.join(src_path,src_file)
                    print(src_path)
                    dst_path=new_path+'\\'+'test'
                    print(dst_path)
                    dst=os.path.join(dst_path)
                    print(src)
                    shutil.copy(src,dst)
                    x+=1

阴性病例集

道理和阳性比例集的读取是一样的,只需修改目的文件夹路径。

for src_file in src_filelist:
                if x<point:
                    src=os.path.join(src_path,src_file)
                    print(src_path)
                    dst_path=new_path+'\\'+'train'
                    print(dst_path)
                    dst=os.path.join(dst_path)
                    print(src)
                    shutil.copy(src,dst)
                    x+=1
                else:
                    src=os.path.join(src_path,src_file)
                    print(src_path)
                    dst_path=new_path+'\\'+'test'
                    print(dst_path)
                    dst=os.path.join(dst_path)
                    print(src)
                    shutil.copy(src,dst)
                    x+=1


本次简单地使用python完成了文件复制的操作,代码写的实在是太太潦草了,还有许多地方需要改进,就当是自己学习过程的一个记录吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值