使用 Barcode 将多个条形码写入一个文件,python

Writing several barcodes to one file using Barcode, python

假设我有一个名为 barcodes.txt 的 text-file,如下所示:

some-13-digit-number
some-other-13-digit-number

我想从这个文件中取出每一行,并在 .svg-file 中输出条形码。这我已经使用条形码完成了:

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

这很好用。不要介意所有遗漏的输入检查,为了使这篇文章简短易读,我删除了很多内容。

问题:我想将每个条形码写入同一个文件,而不是遍历条形码并将每个条形码写入自己的文件。我已经尝试过只写同一个file-name,但这给了我一个header-issue。结果 svg-file 在检查时看起来像这样:

<?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"/>    
        ...

如果我写入同一个文件,这个header会为每个写入的条形码重复,这会导致错误,而且所有条形码(rect-elements)都会重叠。所以我正在寻找不同的解决方案。有什么建议么?如果一个库满足我可以从单个 .txt-file.

中获取所有数字以生成条形码的要求,我愿意使用不同的库

对我来说,解决方案是首先为每一行生成一个文件:

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)