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. P2429 制杖题

    P2429 制杖题这个题用线性筛会WA一个点,因为这个题是给定的质数集,最大的质数会比当前的倍数大,就会出现上面的情况.怎办?判重用set啊!set+线性筛就过掉了.16ms #include< ...

  2. Python3 决策树ID3算法实现

    # -*- coding: utf-8 -*- """ Created on Wed Jan 24 19:01:40 2018 @author: markli 采用信息增 ...

  3. jenkins自动构建部署

    环境 centos7   tomcat8.5.37   maven3.3.9   jdk8   git1.8.3.1 安装jdk,tomcat,maven,git(环境变量,配置文件什么的自行百度) ...

  4. Web大前端面试题-Day1

    1. var的变量提升的底层原理是什么? JS引擎的工作方式是:1) 先解析代码,获取所有被声明的变量:2)然后在运行.也就是说分为预处理和执行两个阶段. 变量提升:所有变量的声明语句都会被提升到代码 ...

  5. BZOJ3772精神污染

    参见http://blog.csdn.net/popoqqq/article/details/43122821 #include<bits/stdc++.h> using namespac ...

  6. BZOJ.3522.[POI2014]Hotel(DP)

    题目链接 BZOJ 洛谷 以为裸点分治,但数据范围怎么这么小?快打完了发现不对.. n^2做的话其实是个水题.. 枚举每一个点为根,为了不重复计算,我们要求所求的三个点必须分别位于三棵子树上. 考虑当 ...

  7. BZOJ.3932.[CQOI2015]任务查询系统(主席树 差分)

    题目链接 对于这一区间的操作,我们可以想到差分+前缀和(感觉也没什么别的了..). 同时对于本题我们能想到主席树,而主席树正是利用前一个节点建树的. 所以离散化.按时间排序,把操作拆成单点加和减即可. ...

  8. ReentrantLock源码了解

    1).ReentrantLock.tryLock //获取没有被其他线程持有的锁 //1).当没有被任何线程持有时,首先将计数器设置为1,并设置当前持有锁的线程为当前线程,最后返回true //2). ...

  9. bzoj4289 Tax

    Description 给出一个N个点M条边的无向图,经过一个点的代价是进入和离开这个点的两条边的边权的较大值,求从起点1到点N的最小代价.起点的代价是离开起点的边的边权,终点的代价是进入终点的边的边 ...

  10. 【汇总】PHP-FPM 配置优化(转)

    -----------------------开启php-fpm慢脚本日志 request_slowlog_timeout = 30sslowlog = /usr/local/php/var/log/ ...