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!

N.Brue
  • 3
  • 2
  • Refer to [python - builtins.TypeError: must be str, not bytes - Stack Overflow](https://stackoverflow.com/questions/5512811/builtins-typeerror-must-be-str-not-bytes) -- although the answer has a little too little explanation, and it's for another library... – user202729 Jan 19 '21 at 14:29
  • Or [python 3.x - How to export qr_code img to disk? - Stack Overflow](https://stackoverflow.com/questions/55007993/how-to-export-qr-code-img-to-disk) – user202729 Jan 19 '21 at 14:30

1 Answers1

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)
vladmihaisima
  • 2,119
  • 16
  • 20
  • 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! – vladmihaisima Jan 24 '21 at 22:28