import cv2
#正则匹配使用:
import re
import os
#此库用于拷贝,删除,移动,复制以及解压缩
import shutil
import numpy as np
#import tensorflow
import matplotlib.pyplot as plt
#如此读取图像,直接返回numpy.ndarray
# img=cv2.imdecode(np.fromfile("C:/Users/104005162/Desktop/企业微信截图_20220212102256.png",np.uint8),-1)
# print(img.shape)
# #转换为bgr图片,注意此时是PNG图片,不能用矩阵直接转换!
# #img=img[:,:,::-1]
# #bgra
# img=cv2.cvtColor(img,cv2.COLOR_BGRA2RGB)
#返回样本的分类序号:
def returnNumClass(path):
if "_" not in path:
print("文件路径非法")
return None
#如果包含路径,提取出数字
else:
return re.findall("_(.*?)\.",path)[0]
#该命令读取某文件夹下所有的文件名:
targetPath="C:/Users/104005162/Desktop/实验文件夹"
path="C:/Users/104005162/Desktop/实验数据"
#在路径下新建文件夹:
for i in range(4):
#如果待创建文件夹不存在,创建文件夹
if not os.path.exists(os.path.join(targetPath,str(i))):
os.makedirs(os.path.join(targetPath,str(i)))
else:
print("待创建文件夹已存在")
fullNameList=[]
listAllFiles=os.listdir(path)
for fileName in listAllFiles:
fullNameList.append(os.path.join(path,fileName))
#判断是否为文件夹
if os.path.isdir(fullNameList[-1]):
#排除最后一个元素
dirName=fullNameList.pop()
print(dirName+"是一个文件夹")
#这种表达方式只能用于删除文件
#os.remove(dirName)
#此种表达方式可以用来删除文件夹
shutil.rmtree(dirName)
#跳过此次
continue
#如果文件提取错误,不返回,只提示
if returnNumClass(fileName)==None:
print("文件名提取路径失败"+fileName)
continue
#将该文件复制进指定的文件夹中:
else:
#这种方法必须是文件名到文件名
shutil.copyfile(os.path.join(path,fileName), os.path.join(os.path.join(targetPath,returnNumClass(fileName)),fileName))
#这种复制可以是文件名到文件夹名
#shutil.copy(os.path.join(path,fileName), os.path.join(targetPath,returnNumClass(fileName)))
print(fullNameList)