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循环遍历 ...
随机推荐
- NOSQL快速入门
NoSql是一个很老的概念了,但对自己来说,仍然是一个短板,果断补上. 首先通过几个简单的例子来了解NOSQL在国内的情况(2013年左右的数据,有些过时),比如新浪微博,其就有200多台物理机运行着 ...
- Mac 下的 .app文件如何生成.dmg ?
安装 Node.js最新版. 安装方法不赘述. 安装 create-dmg: sudo npm install --global create-dmg 注意这里 sudo不能少. 终端切换到 .app ...
- Jindent——让intellij idea 像eclipse一样生成模版化的javadoc注释
插件地址 http://plugins.jetbrains.com/plugin/2170?pr=idea 安装方法参考 http://www.cnblogs.com/nova-/p/3535636. ...
- Codeforces Round #511 (Div. 2)
Codeforces Round #511 (Div. 2) #include <bits/stdc++.h> using namespace std; int n; int main() ...
- HQL的内连接查询
/** * HQL的内连接查询 * String hql="from Customer c inner join fetch c.linkmans"; */ @Test publi ...
- Docker系列之(五):使用Docker Compose编排容器
1. 前言 Docker Compose 是 Docker 容器进行编排的工具,定义和运行多容器的应用,可以一条命令启动多个容器. 使用Compose 基本上分为三步: Dockerfile 定义应用 ...
- CentOS 7解压安装PHP5.6.13
自动化脚本: https://github.com/easonjim/centos-shell/blob/master/php/install-php_5.6.13.sh
- Windows访问Linux的Ext4格式分区
Ext2Fsd是Windows下一套很实用的Driver,虽然名称是ext2fsd但ext3/ext4都可读取,安装完成后电脑便可直接认得ext格式扇区 虽然官方介绍只能支持到Windows 8,但实 ...
- [Go] 判断 文件/文件夹 是否存在?
Golang 判断文件是否存在有点怪异,是根据在操作文件时返回的错误信息来判断的,而不能直接根据路径判断 版本1: func IsExists(path string) (bool, error) { ...
- HTTP协议GET和POST的区别
from http://blog.csdn.net/whuslei/article/details/6667095 权威点的说明请参考:http://www.cs.tut.fi/~jkorpela/f ...