https://blog.csdn.net/ZWX2445205419/article/details/73527857

改进

# coding=utf-8
import os def makeFileLists(imgPath, fileName='list.txt', withLabel=False, ext=['jpg','bmp','png']):
'''
makeFileList 函数用于包含多层目录的文件列表创建
Params:
imgPath :最上层的目录路径
fileName : 列表文件名称
withLabel : 默认为`False`,如果需要为每个图片路劲添加label,
则将该参数设置为`True`,图片所在目录的名称即为
该图片的label
ext : 图片格式
Usage:
makeFileLists('imagesRootPath', 'imageList.txt', False)
'''
# 判断路径是否存在
if not os.path.exists(imgPath):
print imagesPath, 'IS NOT EXIST, PLEASE CHECK IT!' # 判断路径是否为目录,如果是,则对目录下的子目录做递归操作
elif os.path.isdir(imgPath):
subPath = os.listdir(imgPath)
subPath = [os.path.join(imgPath,path) for path in subPath]
for path in subPath:
makeFileLists(path, fileName, withLabel)
# 如果路径不是目录,则为图片的相对路径
else:
# 只保存指定格式的图片
if imgPath[-3:] in ext:
# 以追加的方式打开文件
f = open(fileName,'a')
# 如果需要添加label,则将图片所在目录的名称作为label
if withLabel:
line = imgPath+' '+(imgPath.split('/'))[-2]+'\n'
else:
line = imgPath+'\n'
# 写入文件
f.writelines(line)
f.close() if __name__ == "__main__":
imagesPath = 'val'
fileName = 'val.txt'
makeFileLists(imagesPath, fileName, True)

  

使用递归方式生成包含子目录的文件列表

#coding=utf-8
import os
import shutil
import random def getFileList(filePath='./images'):
print filePath
fileNames = os.listdir(filePath)
paths = filePath.split('/')
print paths
if len(paths) == 4:
fw = paths[2]
f = open('train_'+fw+'.txt','a')
fileList = os.listdir(filePath)
# ./images/-45_45/x9/9_18_-1.29865.jpg
# 根据路径自己组合
saveRootPath = paths[2]+'/'+paths[3]
fileListEnd = [saveRootPath+'/'+line+' '+paths[3][1]+'\n' for line in fileList] # 不要忘记加label
f.writelines(fileListEnd)
f.close() for fn in fileNames:
subPath = filePath+'/'+fn
if os.path.isdir(subPath):
getFileList(subPath) getFileList()

  


#coding=utf-8
#对一批训练数据,里面包含多个文件夹,每个文件夹下面存放的是相同类别的物体
# 根据这些文件夹生成列表、切分验证、训练集数据
import os
import shutil
import random
#因为caffe中,不允许文件名中有空格,所有需要重命名去除空格
def stdrename(imgfiles):
for l in imgfiles:
x_list=l.split(' ')
y = ''.join(x_list)
if l!=y:
print 'rename'
os.rename(l,y) def GetFileList(FindPath,FlagStr=[]):
FileList=[]
FileNames=os.listdir(FindPath)
if len(FileNames)>0:
for fn in FileNames:
if len(FlagStr)>0:
if IsSubString(FlagStr,fn):
fullfilename=os.path.join(FindPath,fn)
FileList.append(fullfilename)
else:
fullfilename=os.path.join(FindPath,fn)
FileList.append(fullfilename) if len(FileList)>0:
FileList.sort() return FileList def spiltdata(path_root,valratio=0.15):
classify_temp=os.listdir(path_root)
classify_file=[]
for c in classify_temp:
classify_file.append(os.path.join(path_root,c)) for f in classify_file:
imgfiles=GetFileList(f)
stdrename(imgfiles)#caffe 文件名不允许有空格
for c in classify_temp:
imgfiles=os.listdir(os.path.join(path_root,c))
nval=int(len(imgfiles)*valratio)
print nval
imgfvals=imgfiles[:nval]
#验证数据文件列表
for j in imgfvals:
if os.path.exists(os.path.join(path_root+'/'+'val',c)) is False:
os.makedirs(os.path.join(path_root+'/'+'val',c))
newname=os.path.join(path_root+'/'+'val',c)+'/'+j
oldname=os.path.join(path_root,c)+'/'+j
shutil.move(oldname,newname)
#训练数据文件列表
imgftrains=imgfiles[nval:]
for j in imgftrains:
if os.path.exists(os.path.join(path_root+'/'+'train',c)) is False:
os.makedirs(os.path.join(path_root+'/'+'train',c))
newname=os.path.join(path_root+'/'+'train',c)+'/'+j
oldname=os.path.join(path_root,c)+'/'+j
shutil.move(oldname,newname) def writetrainlist(path_root):
classify_temp=os.listdir(path_root)#['cropblack','cropbrown','cropwhite','cropyellow']
classify_file=[]
for c in classify_temp:
classify_file.append(os.path.join(path_root,c))
for f in classify_file:
imgfiles=GetFileList(f)
stdrename(imgfiles)#caffe 文件名不允许有空格 sorted(classify_file)
strlist=''
for i,f in enumerate(classify_file):
imgfiles=GetFileList(f)
for image in imgfiles:
print image
strlist+=image+' '+str(i)+'\n' txtlist=open(path_root+'.txt','w')
txtlist.write(strlist)
txtlist.close() '''spiltdata('../headangle/data')'''
# writetrainlist('../faceshape/data/train')
# writetrainlist('../faceshape/data/val') #spiltdata('../hair/data')
#writetrainlist('../hair/data/train')
#writetrainlist('../hair/data/val') writetrainlist('../data/train')
writetrainlist('../data/val')

  

Python生成文件列表的更多相关文章

  1. DOS命令生成文件列表

    DOS命令窗口,生成文件列表命令格式:dir xmlFiles /b >list.txt dir 文件列表相关命令 xmlFiles 待生成文件所在文件夹,在dos命令窗口根目录下,省略前缀.别 ...

  2. 根据BOM和已存在的文件生成文件列表

    在BOM中记录中有物料编码,物料名称,物料规格等,而且依据BOM已经生成了相应的文件,如采购规格书,检验规格书等,这个时候需要获得这些文件的标题,并且生成一个列表,可以使用下面的VBA代码,具体代码如 ...

  3. bat产生随机数并复制文件及生成文件列表

    有这样一个场景:我需要将同一个文件复制为上千个文件,并且文件名应为随机数.为了简单起见,不想写程序,直接写个BAT来,方便,简单,易用: 1. 搞定用BAT产生32位随机数,存为变量并使用,保存以下代 ...

  4. python——获取文件列表

    """-------------------------------------------------------- <<获取文件列表>> () ...

  5. python 生成文件到- execl

    查了一些资料发现是英文版本的 很尴尬,经过看源码,和几个错误 ,现记录下来 一:下载包 pip install xlwt 二:定义样式 def set_style(name, height, bold ...

  6. 用DOS命令获取文件列表

    其实就是两个命令:dir 跟 tree 在C:盘根目录下生成了一个名为“filelist.txt”的文本文件,该文件中即包含D:盘的文件夹列表. dir d:\ >c:\filelist.txt ...

  7. [转载]Python 元组、列表、字典、文件

    python的元组.列表.字典数据类型是很python(there python is a adjective)的数据结构.这些结构都是经过足够优化后的,所以如果使用好的话,在某些area会有很大的益 ...

  8. 用python脚本通过excel生成文件夹树结构

    大概这样写标题是对的吧... 目标: 通过excel目录结构文档生成文件夹树结构. 也就是: 通过下面的excel

  9. python字符串、列表和文件对象总结

    1.字符串是字符序列.字符串文字可以用单引号或者双引号分隔. 2.可以用内置的序列操作来处理字符串和列表:连接(+).重复(*).索引([]),切片([:])和长度(len()).可以用for循环遍历 ...

随机推荐

  1. SQL中的坑

    一.where,group by,having --group by 和having 解释:前提必须了解sql语言中一种特殊的函数:聚合函数, 例如SUM, COUNT, MAX, AVG等.这些函数 ...

  2. 关于Sql Server的一些知识点的定义总结

    数据库完整性:是指数据库中数据在逻辑上的一致性.正确性.有效性和相容性 实体完整性(Entity Integrity  行完整性):实体完整性指表中行的完整性.主要用于保证操作的数据(记录)非空.唯一 ...

  3. codeforces_1092c

    title: codeforces_1092c date: 2018-12-24 19:42:23 tags: acm 刷题 概述 一道有关字符串前缀后缀的题,,,自己迟早要坑在这字符串的题上,,,一 ...

  4. 用js来实现那些数据结构及算法—目录

    首先,有一点要声明,下面所有文章的所有内容的代码,都不是我一个人独立完成的,它们来自于一本叫做<学习JavaScript数据结构和算法>(第二版),人民邮电出版社出版的这本书.github ...

  5. iOS技术篇:sizeToFit 和 sizeThatFits 区别

    sizeToFit:会计算出最优的 size 而且会改变自己的size UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(, , , ...

  6. iOS开发安全 架构

    网络通讯.本地文件和数据.源代码三方面 网络通讯 安全的传输用户密码 客户端在登录时,使用公钥将用户的密码加密后,将密文传输到服务器.服务器使用私钥将密码解密,然后加盐 (Salt:在密码学中,是指通 ...

  7. C#简单的通用分页

    通用分页技术分析 需要返回不同的类型的数据--采用泛型实现该操作 需要提供不同的方法 上一页 上一页 第一页 最后一页 跳转到指定页 Demo 代码 using System; using Syste ...

  8. C#开发Unity游戏教程之Scene视图与脚本的使用

    C#开发Unity游戏教程之Scene视图与脚本的使用 Unity中Scene视图的快捷操作 Scene视图是开发者开发游戏时,操作最频繁的视图.因为一旦一个游戏对象被添加到游戏的场景中,就需要首先使 ...

  9. gson Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path

    返回数据解析错误 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT ...

  10. mySql---数据库索引原理及优化

    一.写在前面 本文以MySQL数据库为研究对象,讨论与数据库索引相关的一些话题.特别需要说明的是,MySQL支持诸多存储引擎,而各种存储引擎对索引的支持也各不相同,因此MySQL数据库支持多种索引类型 ...