1.改后缀
这个代码是指定路径,但是里面的具体文件名不知道,能够罗列所有的指定文件名和修改后缀,如果要获取具体路径下的文件文件名和后缀看下面这个目录
import os
def read_evr_yuc(file_path):
dirpaths=os.listdir(file_path)
yuv_name=[]
name=[]
new_name=[]
for i in dirpaths:
yuv_name.append(i)
portion=os.path.splitext(i) #把文件名拆分为名字和后缀
if portion[1] == ".yuv": #指定里面所有yuv的后缀的文件
newname = portion[0] + ".code"
new_name.append(newname)
name.append(portion[0])
print(yuv_name)
print(name)
print(new_name)
if __name__ == '__main__':
file_path='D:/pycharm/match/huffman/yuc_file/'
read_evr_yuc(file_path)
2.划分路径和文件名、后缀名
#########start 获取文件路径、文件名、后缀名############
def get_splitfile(filename):
(filepath,tempfilename) = os.path.split(filename)
(shotname,extension) = os.path.splitext(tempfilename)
print(filepath)
print(shotname)
print(extension)
return filepath,shotname,extension
#########end 获取文件路径、文件名、后缀名############
path='F:/Dataset/cool/1.jpg'
get_splitfile(path)
3.指定目录下所有的图片写入到txt文档
"""把指定目录下所有的图片写入到txt文档中"""
import os
img_path='F:/pycharm/Pytorch2TensorRT-master/face/'
txtfile='F:/pycharm/Pytorch2TensorRT-master/my_files/face.txt'
os.makedirs(os.path.dirname(txtfile),exist_ok=True)
dirpaths=os.listdir(img_path)
f=open(txtfile,'w')
for dirpath in dirpaths:
# print(dirpath)
path=os.path.join(img_path,dirpath)
print(path)
f.write(path+'\n')
4.指定目录下所有的子目录(写上对应的label)对应的所有图片写入到csv文档
import os,glob,cv2,random,csv
def work():
name2label = {}
path='pokemon/'
for name in sorted(os.listdir(os.path.join(path))):
# 得到全部子目录
if not os.path.isdir(os.path.join(path, name)):
# 用于判断对象是否为一个目录
continue
name2label[name] = len(name2label.keys())
print(name2label)
images = []
for name in name2label.keys():
images += glob.glob(os.path.join(path, name, '*.png'))
images += glob.glob(os.path.join(path, name, '*.jpg'))
images += glob.glob(os.path.join(path, name, '*.jpeg'))
# print(len(images), images)
random.shuffle(images)
with open(os.path.join(path, 'face.csv'), mode='w', newline='') as f:
writer = csv.writer(f)
for img in images: # 'pokemon\\bulbasaur\\00000000.png' os.sep不用距离根据\\和/进行划分
print(img)
img=img.replace('\\','/') # 将里面的\换/
# name = img.split(os.sep)[-2]
(filepath, tempfilename) = os.path.split(img) # 获取路径、图片文件名
(filepath1, tempfilename1) = os.path.split(filepath) # 获取剩余路径下的文件路径、文件名
(filename, extension) = os.path.splitext(tempfilename1) # 获取文件路径、文件名
print(filename)
label = name2label[filename]
# pokemon/squirtle/00000183.jpg 4
writer.writerow([img, label])
print('writen into csv file:', filename)
# read from csv file
images, labels = [], []
with open(os.path.join(path, 'face.csv')) as f:
reader = csv.reader(f)
for row in reader:
# pokemon/squirtle\00000183.jpg 4
img, label = row
label = int(label)
images.append(img)
labels.append(label)
assert len(images) == len(labels)
return images,labels
images,labels=work()
print(images,labels)