将文件保存在python中的目录中

2024-05-10 04:52:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在我的应用程序中为每个项目创建条形码

代码如下:

from base64 import b64encode
from reportlab.lib import units
from reportlab.graphics import renderPM
from reportlab.graphics.barcode import createBarcodeDrawing
from reportlab.graphics.shapes import Drawing

def get_barcode(value, width, barWidth = 0.05 * units.inch, fontSize = 30):

    barcode = createBarcodeDrawing('Code128', value = value, barWidth = barWidth, fontSize = fontSize)

    drawing_width = width
    barcode_scale = drawing_width / barcode.width
    drawing_height = barcode.height * barcode_scale

    drawing = Drawing(drawing_width, drawing_height)
    drawing.scale(barcode_scale, barcode_scale)
    drawing.add(barcode, name='barcode')
    return drawing

sku = ['A100', 'A101', 'A102', 'A103', 'A104', 'A105', 'A106', 'A107', 'A108', 'A109']

for i in sku:
    barcode = get_barcode(value = i, width = 600)
    data = b64encode(renderPM.drawToString(barcode, fmt = 'PNG'))

如何将每个文件保存在桌面位置,即r'C:\Users\Rahul\Desktop',文件名为SKU名称


Tags: fromimportvaluewidthbarcodeunitsheightscale
1条回答
网友
1楼 · 发布于 2024-05-10 04:52:30

这是否适用于您(更改输出路径)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'g3n35i5'

import os
import base64
from reportlab.lib import units
from reportlab.graphics import renderPM
from reportlab.graphics.barcode import createBarcodeDrawing
from reportlab.graphics.shapes import Drawing


def get_barcode(value, width, barWidth=0.05 * units.inch, fontSize=30):
    barcode = createBarcodeDrawing('Code128', value=value, barWidth=barWidth, fontSize=fontSize)

    drawing_width = width
    barcode_scale = drawing_width / barcode.width
    drawing_height = barcode.height * barcode_scale

    drawing = Drawing(drawing_width, drawing_height)
    drawing.scale(barcode_scale, barcode_scale)
    drawing.add(barcode, name='barcode')
    return drawing


sku = ['A100', 'A101', 'A102', 'A103', 'A104', 'A105', 'A106', 'A107', 'A108', 'A109']

output_path = '/tmp/barcodes/'
if not os.path.exists(output_path):
    os.mkdir(output_path)

for i in sku:
    barcode = get_barcode(value=i, width=600)
    data = base64.b64encode(renderPM.drawToString(barcode, fmt='PNG'))
    filename = os.path.join(output_path, f"{i}.png")
    with open(filename, "wb") as fh:
        fh.write(base64.decodebytes(data))

相关问题 更多 >