You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从列表批量生成多个条形码?Python实现问题与解决

批量生成条形码脚本的错误修正

问题场景

需要编写Python脚本,读取TXT文件中每行的条形码内容,批量生成对应的条形码图片。原代码因循环逻辑错误,最终只生成一个包含所有条码内容的图片,而非每个内容单独生成。

原代码

from PIL import Image
import barcode
from tkinter import *
from tkinter import filedialog
import os
from barcode.writer import ImageWriter

options = {
    'dpi': 1100,
    'font_size':15,
    'module_height': 7,
    'text_distance':12.0,
    }

image_path="C:/Users/*/Desktop/Created Barcodes"

textFile= filedialog.askopenfilename()
  
f= open(textFile, "r").readlines()
for i in f:
    lines = [i.strip() for i in f]
    print(lines)
    number = (f"{lines}")

barcode_format = barcode.get_barcode_class('code128')

# 生成条形码并渲染为图片
image_writer = ImageWriter().set_options(options)
image = barcode_format(number, writer=ImageWriter(),)
  
isExist = os.path.exists(image_path)
if not isExist:
    os.mkdir(image_path)
  
# 保存条形码为PNG文件    
image= image.save(rf"{image_path}/{number}")

错误分析

问题出在循环部分:

for i in f:
    lines = [i.strip() for i in f]
    print(lines)
    number = (f"{lines}")
  • 遍历文件对象f时,内部列表推导式会一次性读取完所有文件内容,导致外层循环仅执行一次
  • number被赋值为整个列表的字符串形式(如['code1', 'code2']),最终生成的条形码内容是整个列表,而非单个条码值

修正后的代码

import barcode
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
import os
from barcode.writer import ImageWriter

options = {
    'dpi': 800,
    'font_size':1,
    'module_height': 0.5,
    'module_width': 100.0,
    'text_distance':5.0,
}

try:
    
    image_path= os.path.join(os.environ['USERPROFILE'],'Desktop','Generated')

    textFile= filedialog.askopenfilename()
  
    f= open(textFile, "r").readlines()
    
    lines = [i.strip() for i in f]
    
    barcode_format = barcode.get_barcode_class('code128')
    
    # 遍历TXT文件中的每一行内容
    for code in lines:
        image_writer = ImageWriter().set_options(options)
        image = barcode_format(code, writer=ImageWriter(),)
        # 生成条形码并渲染为图片
    
        if not os.path.isdir(image_path):
            os.mkdir(image_path)
         
        # 保存条形码为PNG文件    
        image.save(rf"{image_path}/{code}")
    messagebox.showinfo("成功", "条形码已批量生成完成!")
except :
    messagebox.showerror("错误", "操作失败,请重试!")

修正要点

  • 先一次性读取并处理所有行到lines列表,避免文件指针异常
  • 循环遍历lines中的每个条码值,逐个生成对应的条形码图片
  • 使用os.environ['USERPROFILE']构建保存路径,适配不同用户目录
  • 增加try-except异常捕获和消息框提示,提升用户体验
  • 调整条形码生成参数,优化输出效果
  • 用os.path.isdir判断目录是否存在,创建逻辑更严谨

内容的提问来源于stack exchange,提问作者Fenris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 05:40:30