读取文件夹下所有文件
img_path = r'E:/workspace/PyCharmProject/dem_feature/dem\512/label'
save_txt_path = r'./images.txt'
imgs = os.listdir(img_path)
过滤:只保留png结尾的图片
names = []
for img in imgs:
if img.endswith(".png"):
names.append(img)
创建txt文件并逐行写入
txt = open(save_txt_path,'w')
for name in names:
name = name[:-4]
txt.write(name + '\n')
txt.close()
完整代码
"""
#-*-coding:utf-8-*-
# @author: wangyu a beginner programmer, striving to be the strongest.
# @date: 2022/7/7 20:25
"""
import os
img_path = r'E:/workspace/PyCharmProject/dem_feature/dem/512/label'
save_txt_path = r'./images.txt'
imgs = os.listdir(img_path)
names = []
for img in imgs:
if img.endswith(".png"):
names.append(img)
txt = open(save_txt_path,'w')
for name in names:
name = name[:-4]
txt.write(name + '\n')
txt.close()