首先给出代码:
import os path = "/home/data//"path_exp = os.path.expanduser(path)classes = [int(p) for p in os.listdir(path_exp)]classes.sort()# nrof_classes一个数据集下有多少个文件夹,就是说有多少个人,多少个类别nrof_classes = len(classes)count=0files = open("train_list.txt",'w')filets = open("test_list.txt",'w')count_u=0for i in range(nrof_classes): class_name = str(classes[i]) count=count+1 count_u=count_u+1 facedir = os.path.join(path_exp, class_name) prefix1 = path+class_name+"/" if os.path.isdir(facedir): images = os.listdir(facedir) #print(images[0]) image_paths = [(prefix1+img+" "+class_name+"/n") for img in images] #print(image_paths[0]) if count < 0.8*nrof_classes: if len(image_paths)>4: test_path=[] for x in range(2): test_path.append(image_paths[0]) del image_paths[0] filets.writelines(test_path) files.writelines(image_paths) #if count==2: # break #imgae_pathses = [] #防止图像大小为0 #for x in image_paths: # if os.path.getsize(x)>0: # imgae_pathses.append(x) #if len(imgae_pathses)==0: # os.rmdir(facedir)files.close()filets.close()
python下os模块的一下有用的用法:
0 重命名:文件和文件夹都是一个命令:
os.rename(original_dir,new_dir)
1 文件操作:
os.mknod("test.txt") 创建空文件
fp = open("test.txt",w) 直接打开一个文件,如果文件不存在则创建文件
关于open 模式:
w 以写方式打开,
a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+ 以读写模式打开
w+ 以读写模式打开 (参见 w )
a+ 以读写模式打开 (参见 a )
rb 以二进制读模式打开
wb 以二进制写模式打开 (参见 w )
ab 以二进制追加模式打开 (参见 a )
rb+ 以二进制读写模式打开 (参见 r+ )
wb+ 以二进制读写模式打开 (参见 w+ )
ab+ 以二进制读写模式打开 (参见 a+ )
fp.read([size]) #size为读取的长度,以byte为单位
fp.readline([size]) #读一行,如果定义了size,有可能返回的只是一行的一部分
fp.readlines([size]) #把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。
新闻热点
疑难解答