Python: To generate a qrcode – UPDATE
I have updated my little Python script from 29.09.2025.
Updates:
The modules pathlip and os were imported.
Clear the screen (def clear screen). I think that it is better to have a clear screen as you the script begins in the middle of the monitor. The clear command is for Windows and Linux, Unix and BSD (Berkley Software Distribution like FreeBSD, OpenBSD, NetBSD etc.).
User input – the user can now add directly an own file name
User input – the user can now add directly his own save location (where do you want to save the QR-Code)
checking function whether the directory really exists – otherwise he will get an error message. In my opinion, it is better to use a directory that already exists.
import qrcode
from pathlib import Path
import os
# --- Help function: Clear screen ---
def clear_screen():
if os.name == 'nt':
# for Microsoft Windows
os.system('cls')
else:
# for Linux, macOS (posix systems)
os.system('clear')
# --- Main function: Generates and saves the QR code ---
def generate_qr_code():
# 1. clear the screen
clear_screen()
# 2. create QR-Object
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
# add the data
qr.add_data("https://sven-essen.de")
qr.make(fit=True)
# create image
img = qr.make_image(fill_color="black", back_color="white")
# 3. collect the user input
data_name_input = input("Please add the file name (e.g., 'mein_code'): ")
file_name_with_ext = data_name_input + ".png"
wheretosave_str = input("Where you want to save your QR-Code? Please add the directory /home/sven/directory/directory: ")
# 4. validate the path
wheretosave_path = Path(wheretosave_str)
print("Checking whether the directory exists:", wheretosave_path.exists())
if wheretosave_path.is_dir() and wheretosave_path.exists():
final_path = wheretosave_path / file_name_with_ext
# save
try:
img.save(final_path)
print(f"\nQR-Code save successfully in: {final_path}")
except Exception as e:
# error during the writing
print(f"\nError: Could not save the file. Reason: {e}")
else:
print("\nError: Your directory does not exists or is not valid.")
# --- execution point ---
# This ensures that the function only runs when the script is executed directly.
if __name__ == "__main__":
generate_qr_code()