python读取文件夹中的所有图片并将图片名逐行写入txt中

x33g5p2x  于2022-07-26 转载在 Python  
字(0.9k)|赞(0)|评价(0)|浏览(396)

读取文件夹下所有文件

# 文件夹路径
img_path = r'E:/workspace/PyCharmProject/dem_feature/dem\512/label'
# txt 保存路径
save_txt_path = r'./images.txt'

# 读取文件夹中的所有文件
imgs = os.listdir(img_path)

过滤:只保留png结尾的图片

# 图片名列表
names = []

# 过滤:只保留png结尾的图片
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]    # 去掉后缀名.png
    txt.write(name + '\n')  # 逐行写入图片名,'\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'
# txt 保存路径
save_txt_path = r'./images.txt'

# 读取文件夹中的所有文件
imgs = os.listdir(img_path)

# 图片名列表
names = []

# 过滤:只保留png结尾的图片
for img in imgs:
    if img.endswith(".png"):
        names.append(img)

txt = open(save_txt_path,'w')

for name in names:
    name = name[:-4]    # 去掉后缀名.png
    txt.write(name + '\n')  # 逐行写入图片名,'\n'表示换行

txt.close()

相关文章