0

Im am currently trying to generate QR codes for the keys of a dictionary.If I try that for one key only, it is no problem at all. However, if I try to automatize the process, incrementing my file number for each key, I only generate empty .png files.

For one QR code at a time, my code works and looks like this: import cv2 import os import qrcode

test = {
    1: { "gene": "aox1a", "construct": "2-23", "line": "8" },
    2: { "gene": "aox1a", "construct": "2-23", "line": "8 " },
    3: { "gene": "aox1a", "construct": "2-23", "line": "8" }
}


data = "This is plant 1", test[1]
# output file name
filename = "plant1.png"
# generate qr code
img = qrcode.make(data)
# save img to a file
img.save(filename)

Like that, I generate one .png file containing the desired QR code, that says: "This is plant 1', {'gene':'aox1a' .....}) If I try the automation with a loop, it looks like that:

for i in test.keys():
    data=test[i]
    print(test[i])
    i = 0
    while os.path.exists("pic%s.png" % i):
        i += 1
    filename = open("pic%s.png" % i, "w")

This is the point to where my code works ok. However, I have no idea how I could no pick uo those files and put my QR codes in. If I try to add the image like before, using:

img = qrcode.make(data)
# save img to a file
img.save(filename)

it would tell me that 'write() argument must be str, not bytes'.

Can anyone help? Thanks already!

2

1 Answer 1

0

In your first code filename is a string. In the for loop you open the file and make filename a handle to a file. This works for me:

import os import qrcode

test = {
    1: { "gene": "aox1a", "construct": "2-23", "line": "8" },
    2: { "gene": "aox1a", "construct": "2-23", "line": "8 " },
    3: { "gene": "aox1a", "construct": "2-23", "line": "8" } }

for i in test.keys():
    data = test[i]
    print(test[i])
    i = 0
    while os.path.exists("pic%s.png" % i):
        i += 1
    filename = "pic%s.png" % i
    img = qrcode.make(data)
    img.save(filename)
Sign up to request clarification or add additional context in comments.

1 Comment

Hi @N.Brue as the answer solved your issue please consider accepting it by clicking the check-mark. This is the habit on stackoverflow and indicates to the wider community that you've found a solution and gives some reputation to both the person that answered and to yourself, and informs other people they do not need to check the question. Glad it worked!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.