Python生成文件列表
改进
# 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生成文件列表的更多相关文章
- DOS命令生成文件列表
DOS命令窗口,生成文件列表命令格式:dir xmlFiles /b >list.txt dir 文件列表相关命令 xmlFiles 待生成文件所在文件夹,在dos命令窗口根目录下,省略前缀.别 ...
- 根据BOM和已存在的文件生成文件列表
在BOM中记录中有物料编码,物料名称,物料规格等,而且依据BOM已经生成了相应的文件,如采购规格书,检验规格书等,这个时候需要获得这些文件的标题,并且生成一个列表,可以使用下面的VBA代码,具体代码如 ...
- bat产生随机数并复制文件及生成文件列表
有这样一个场景:我需要将同一个文件复制为上千个文件,并且文件名应为随机数.为了简单起见,不想写程序,直接写个BAT来,方便,简单,易用: 1. 搞定用BAT产生32位随机数,存为变量并使用,保存以下代 ...
- python——获取文件列表
"""-------------------------------------------------------- <<获取文件列表>> () ...
- python 生成文件到- execl
查了一些资料发现是英文版本的 很尴尬,经过看源码,和几个错误 ,现记录下来 一:下载包 pip install xlwt 二:定义样式 def set_style(name, height, bold ...
- 用DOS命令获取文件列表
其实就是两个命令:dir 跟 tree 在C:盘根目录下生成了一个名为“filelist.txt”的文本文件,该文件中即包含D:盘的文件夹列表. dir d:\ >c:\filelist.txt ...
- [转载]Python 元组、列表、字典、文件
python的元组.列表.字典数据类型是很python(there python is a adjective)的数据结构.这些结构都是经过足够优化后的,所以如果使用好的话,在某些area会有很大的益 ...
- 用python脚本通过excel生成文件夹树结构
大概这样写标题是对的吧... 目标: 通过excel目录结构文档生成文件夹树结构. 也就是: 通过下面的excel
- python字符串、列表和文件对象总结
1.字符串是字符序列.字符串文字可以用单引号或者双引号分隔. 2.可以用内置的序列操作来处理字符串和列表:连接(+).重复(*).索引([]),切片([:])和长度(len()).可以用for循环遍历 ...
随机推荐
- HttpClient-----待补充
1.简介 HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 java.net 包中 ...
- thinkphp中table方法
table方法也属于模型类的连贯操作方法之一,主要用于指定操作的数据表. 用法 一般情况下,操作模型的时候系统能够自动识别当前对应的数据表,所以,使用table方法的情况通常是为了:切换操作的数据表: ...
- centos7 静默安装oracle
系统centos7.4 mini 关闭selinux.firewalld 配置主机名: hostnamectl set-hostname --static oracle 之前说oracle不认cen ...
- 【FFT&NTT 总结】
$FFT$总结 (因为还不会啊,,都没做过什么题,所以一边学一边打咯.. 1.主要是用来加速卷积形式的求和吧? $F*G(n)=F[i] × G[n-i]$ 平时是$O(n^2)$的,FFT可以$O( ...
- 中断 http请求 正在加载 取消http请求
中断 http请求 正在加载 取消http请求
- Western Subregional of NEERC, Minsk, Wednesday, November 4, 2015 Problem H. Parallel Worlds 计算几何
Problem H. Parallel Worlds 题目连接: http://opentrains.snarknews.info/~ejudge/team.cgi?SID=c75360ed7f2c7 ...
- UVALive 6893 The Big Painting hash
The Big Painting 题目连接: http://acm.hust.edu.cn/vjudge/contest/view.action?cid=122283#problem/J Descri ...
- IntraWeb XIV 类型速查表
tkClass ================== IWUserSessionBase.TIWUserSessionBase < TDataModule < TComponent < ...
- BrowserLog——使用Chrome控制台作为Log查看器
Chrome控制台是十分强大的,即使将它作为一个log查看器也是非常强大的,BrowserLog就是一个.net下的把Chrome作为log输出的程序包. 原理非常简单,server端将log数据通过 ...
- 在触屏设备上面利用html5裁剪图片
前言 如今触屏设备越来越流行,并且大多数已经支持html5了.针对此.对触屏设备开发图片裁剪功能, 让其能够直接处理图片.减轻服务端压力. 技术点 浏览器必须支持html5,包含fileReader. ...