【发布时间】:2018-11-26 23:33:09
【问题描述】:
假设我有一个名为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 文件中获取所有数字以生成条形码的要求,我愿意使用不同的库。
【问题讨论】: