Python Forum

Full Version: Random Ints to Str Problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey all,

I am currently trying to simulate a project I am undertaking in Python 3.7, idea is to randomize some serial numbers and write them to a .TXT file and read from it. It creates the .TXT file and reads ok but the serial number never changes (Random) just wondering if anyone could give me some pointers on how to solve this?

My code is below...

import random
from datetime import datetime

# Using random to simulate barcode scan
serial_No = random.randint(100, 10000000000000)
serial_Desc = ["Nimbus Front Case", "Nimbus Pressure Control Assy", "Nimbus Power Cable"]
user_name = ["Grant Peach", "Brett Stewert", "Barry Harnett", "Roberto Delguadio"]
date_now = datetime.now()
cage_Ref = "Repair Cage 1"

while serial_No >= 10000000000:
    print("\nCreating Serial Log...\n")
    text_file = open("Scanner_Log.txt", "a")
    text_file.write("Barcode No: ")
    text_file.write(str(serial_No))
    text_file.write("\n")
    text_file.write("Item Description: ")
    text_file.write(random.choice(serial_Desc))
    text_file.write("\n")
    text_file.write("Barcode Scanned by: ")
    text_file.write(random.choice(user_name))
    text_file.write("\n")
    text_file.write("On: ")
    text_file.write(str(datetime.now()))
    text_file.write("\n")
    text_file.write("From: ")
    text_file.write(cage_Ref)
    text_file.write("\n")
    text_file.write("\n")
    text_file.close()
    print("Serial Log Created\n")
    # Reading TXT File
    print("Now reading the Serial log...\n")
    text_file = open("Scanner_log.txt", "r")
    print(text_file.read())
else:
    print("Error Reading or Creating TXT file")
Thanks in advance Smile
Hello,
The "random" part of your script (serial_No = random.randint...) is not in the while loop, so it executes only once, and you get only one number. You should put it inside the while loop.
For working with files, you want to use context manager (with) instead of open and close.
Also, having a serial number size as terminate condition of a while loop is a bit odd. To me it sounds more sensible to have a for loop executing a fixed amount of times -> how many serial numbers you want. But that of course is your design decision :)
That has worked a treat, thanks for your help much appreciated! Dance