python将一个文件夹下图片保存在txt文本

本文介绍了一个简单的Python脚本,该脚本可以遍历指定文件夹内的所有图片,并将图片名称(不包含扩展名)保存到一个TXT文件中。此方法适用于自动化整理大量图片文件名的场景。
#!/usr/bin/env python 
# -*- coding:utf-8 -*-
# 将一个文件夹下图片保存在txt文本
import sys
sys.path.append('D:\\train\\img\\image_valid') (图片文件夹)
import os
import random
img_dir = 'D:\\train\\img\\image_valid'
file_list = []
write_dir_name = 'D:\\train\\img\\img_valid.txt'  (图片文件名,不含jpg)
write_file = open(write_dir_name, "w")
for file in os.listdir(img_dir):
##    if file.endswith(".jpg"):
    write_name = file
    write_name1 = write_name.split('.')
    print(write_name1)
    write_name2 = write_name1[0]
    print(write_name2)
    file_list.append(write_name2)
    sorted(file_list)
num = len(file_list)
for current_line in range(num):
    write_file.write(file_list[current_line] + '\n')
write_file.close()

 

假设你的项目目录结构如下: ``` project/ │ ├── image_list.txt # 文本文件,每行一个图片文件名(如:photo1.jpg) ├── images/ # 存放所有图片的源文件夹 │ ├── photo1.jpg │ ├── photo2.png │ └── ... └── output/ # 用于保存复制图片的目标文件夹(可选,也可以直接保存在同级目录) ``` 你的需求是: - 读取 `image_list.txt` 中的图片名称; - 从 `images/` 文件夹中找到这些图片; - 将它们复制到当前目录或指定输出目录(比如 `output/`)。 以下是使用 Python 实现该功能的完整代码: ```python import os import shutil # 配置路径 txt_file = 'image_list.txt' # 存放图片名的文本文件 source_dir = 'images' # 图片原始存放文件夹 output_dir = '.' # 输出目录,'.' 表示当前目录,也可设为 'output' # 确保输出目录存在 os.makedirs(output_dir, exist_ok=True) # 读取txt文件中的图片名 try: with open(txt_file, 'r', encoding='utf-8') as f: image_names = [line.strip() for line in f if line.strip()] # 去除空行和空白字符 except FileNotFoundError: print(f"错误:找不到文件 {txt_file}") exit(1) # 复制对应的图片 not_found = [] for image_name in image_names: source_path = os.path.join(source_dir, image_name) target_path = os.path.join(output_dir, image_name) if os.path.exists(source_path): shutil.copy2(source_path, target_path) print(f"已复制: {image_name}") else: not_found.append(image_name) print(f"未找到: {image_name}") # 输出未找到的文件 if not_found: print("\n以下文件未在源目录中找到:") for name in not_found: print(f" - {name}") else: print(f"\n所有图片均已成功复制到: {os.path.abspath(output_dir)}") ``` ### ✅ 代码解释: - `open(..., encoding='utf-8')`: 安全地读取文本文件,防止中文乱码。 - `line.strip()`:去除每行首尾的换行符、空格等。 - `os.makedirs(output_dir, exist_ok=True)`: 创建输出目录,如果已存在则不报错。 - `shutil.copy2()`: 复制文件并保留元数据(比 `copy` 更安全)。 - 错误处理:检查文件是否存在,提示用户哪些没找到。 --- ### 💡 使用前注意事项: 1. 确保 `image_list.txt` 每行只写图片文件名,例如: ``` photo1.jpg photo2.png image_003.gif ``` 2. 确保这些图片确实存在于 `images/` 目录下。 3. 如果你想把图片保存到单独的文件夹(如 `output/`),可以把 `output_dir = 'output'`,然后程序会自动创建它。 4. 支持常见格式:`.jpg`, `.png`, `.gif`, `.bmp` 等,只要名字匹配即可。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值