Search code examples
pythonpandascsvqr-code

QR Code code inserting '[' and ']', how to stop this?


I'm trying to loop through a list of ~3,000 URLs and create QR codes for them. In one column I have the URLs and in another column I have what I want the QR code file names to be named when output as images.

The problem is the URLs that get converted to QR codes and my file names both come out encased in brackets.

For example:

URL            Filename
www.abel.com   Abel

Comes out as:

URL in QR Code   Filename of QR Code
[www.abel.com]   [Abel]

Here's my code so far:

import csv
import qrcode
import pandas as pd

df = pd.read_csv('QR_Python_Test.csv')

i = 1
x = df.iloc[[i]]
 
print(
x.QR_Code_Name.values)
for i in df.index:
    z = df.iloc[[i]]
    x = str(z.Link_Short.values)
    qr = qrcode.QRCode(version=5, error_correction=qrcode.constants.ERROR_CORRECT_L,box_size=5,border=2,)
    qr.add_data(x)
    qr.make(fit=True)
    img = qr.make_image()
    file_name = str(z.QR_Code_Name.values) + ".png"
    print('Saving %s' % file_name)
    image_file = open(file_name, "w")
    img.save(file_name)
    image_file.close()
file.close()

And some sample data:

URL               Filename
www.apple.com      Apple
www.google.com     Google
www.microsoft.com  Microsoft
www.linux.org      Linux

Solution

  • If your DataFrame contains the correct information, you can use DataFrame.itertuples

    also separate the functions

    • reading the data from the file
    • generating the qr-code
    • saving the files

    That way, you can test each of these individually

    def generate_images(df):
        for row in df.itertuples():
            yield row.Filename, generate_qr(row.URL)
    
    def generate_qr(url):
        qr = qrcode.QRCode(version=5, error_correction=qrcode.constants.ERROR_CORRECT_L,box_size=5,border=2,)
        qr.add_data(url)
        qr.make(fit=True)
        return qr.make_image()
    
    def save_qr_code(qr_codes):
        for filename, qr_code in qr_codes:
            filename = filename + '.png'
            print('saving to file %s' % (filename,)
            with open(filename, 'wb') as file:
                qr_code.save(file)
    
    df = pd.read_csv('my_data.csv')
    
    qr_codes = generate_images(df)
    
    save_qr_code(qr_codes)