# -*- coding: utf-8 -*-
#将文件夹中图像的名字放在一个txt文件中
# 不知道为什么效果不是很好,到是也可以放进去,但是顺序不对
# P01 批量读取文件名,并将读取的文件名保存到指定路径下的txt中(带.*** 后缀)
import os
def ListFilesToTxt(dir, file, wildcard, recursion):
exts = wildcard.split(" ")
files = os.listdir(dir)
for name in files:
fullname = os.path.join(dir, name)
if (os.path.isdir(fullname) & recursion):
ListFilesToTxt(fullname, file, wildcard, recursion)
else:
for ext in exts:
if (name.endswith(ext)):
file.write(name + "\n")
break
def ReadName():
dir = "/home/robot/pictures/img_tracker" # 读取文件路径
outfile = "/home/robot/pictures/imgname.txt" # 将文件名写入Image.txt
wildcard = ".png" # 读取jpg图片
# wildcard = ".jpg .txt .exe .dll .lib" #要读取的文件类型;
file = open(outfile, "w")
if not file:
print("cannot open the file %s for writing" % outfile)
ListFilesToTxt(dir, file, wildcard, 1)
file.close()
ReadName()
上面的程序在ubuntu下图片的名称在txt文件中是乱序的 ,
现在和上一篇文章中的按照原来文件中图片中的顺序重新命名,写了一个按照按照原来顺序将名称放入txt文件中
#- * - coding : utf - 8 - * -
import os
imgDirName = "/home/robot/pictures/img_tracker/"
txtDirName = "/home/robot/pictures/imgname.txt"
list_img_name = []
list_read_img = []
def delete_end_str(path,txtPath):
filelist = os.listdir(path)
txtfile = open(txtPath,"w")
for filename in filelist:
filename = path + filename
list_img_name.append(filename)
new_file_name = filename.split(".png")[0]
list_read_img.append(new_file_name)
list_read_img.sort()
for i in range(len(list_read_img)):
old_img_name = list_read_img[i] + ".png"
new_file_name = path + str(i) + ".png"
txt_img_name = str(i)+".png"
os.rename(old_img_name, new_file_name)
txtfile.write(txt_img_name + "\n")
delete_end_str(imgDirName,txtDirName)