python - 使用 Barcode,python 将多个条形码写入一个文件
问题描述
假设我有一个名为barcodes.txt 的文本文件,如下所示:
some-13-digit-number
some-other-13-digit-number
我想从这个文件中取出每一行并在 .svg 文件中输出条形码。我已经使用 Barcode 完成了这项工作:
import barcode as bc
import os
path = os.path.dirname(os.path.abspath(__file__))
read_file = 'barcode.txt'
lines = (line.rstrip('\n') for line in open(path+read_file))
i = 0
for line in lines:
image = bc.get_barcode_class('ean13')
image_bar = image(u'{}'.format(int(line))) # This is byte-data as I understand it.
barcode_file = open(path+'ean'+str(i)+'.svg', 'wb')
image_bar.write(barcode_file)
i += 1
这工作得很好。别介意所有缺失的输入检查,我删除了很多内容以使其简短易读。
问题:我想将每个条形码写入同一个文件,而不是遍历条形码并将每个条形码写入自己的文件中。我已经尝试过直接写入相同的文件名,但这给了我一个标题问题。生成的 svg 文件在检查时看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg
PUBLIC '-//W3C//DTD SVG 1.1//EN'
'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>
<svg height="23.000mm" version="1.1" width="44.000mm" xmlns="http://www.w3.org/2000/svg">
<!--Autogenerated with python-barcode 0.9.0-->
<g id="barcode_group">
<rect height="100%" style="fill:white" width="100%"/>
<rect height="15.000mm" style="fill:black;" width="0.330mm" x="6.500mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.330mm" x="6.830mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.330mm" x="7.160mm" y="1.000mm"/>
...
如果我写入同一个文件,每个写入的条形码都会重复这个标题,这会导致错误,而且所有的条形码(矩形元素)都会重叠。所以我正在寻找不同的解决方案。有什么建议么?如果一个库满足我可以从单个 .txt 文件中获取所有数字以生成条形码的要求,我愿意使用不同的库。
解决方案
对我来说,解决方案是首先为每一行生成一个文件:
for line in lines:
filename = "ean"+str(i)+".png"
barcodefilepath = barcodeimagefolder/filename
if len(line) == 12 or len(line) == 13: #Let's assume these are ean13-barcodes.
image = bc.get_barcode_class('ean13')
image_bar = image(u'{}'.format(int(line)), writer=ImageWriter(), text_distance=1)
barcode_file = open(barcodefilepath, "wb")
image_bar.write(barcode_file)
barcode_file.close()
i += 1
然后我将所有这些文件添加到列表中:
files_and_dirs = Path(barcodeimagefolder).glob('**/*')
images = [x for x in files_and_dirs if x.is_file() and x.suffix == '.png']
并在 Pandas 数据框中链接到它们:
imagedata = list()
for image in images:
imagedata.append("<img src='barcodeimages/{0}' width='200'>".format(image.name))
d = {'Barcodes': imagedata}
df = pd.DataFrame(data=d)
然后我可以通过 wkhtmltopdf 将其保存为 HTML 或 PDF。最后我删除了所有临时文件:
files = glob.glob(str(barcodeimagefolder.resolve())+'/ean*')
for ean_image in files:
os.remove(ean_image)
推荐阅读
- python - 按钮的 font_size 取决于其小部件(按钮)的大小
- python-3.x - 登录 - 使用枚举方法将用户名和密码与文件进行比较
- javascript - 用于换行文本的断词
- javascript - JQuery用.text()替换div的内容不起作用
- jenkins - 如何修复'hudson.remoting.ProxyException:groovy.lang.MissingMethodException:没有方法签名:testFunc.call()'
- python - 无法从网站上抓取受保护的电子邮件
- python - 如何将实例列表同步到 Python 中的原始实例列表?
- c# - 如何处理与 API 中预期结构不同的 Json Post
- docker - 将 vmtoolsd 挂载到 docker 容器
- dart - Flutter中没有上下文的AlertDialog