I am trying to use a loop to write randomly generated numbers to a text document. Then, using a different program, I need to use a loop to read the numbers. The first program needs to output the numbers in the SAME LINE, the second program needs to output them in DIFFERENT LINES (their own, one per line) Here is what I have:

**The write one works, I can't get the read one to become a float.

for the first program (write)

import random
def main(): 
    one = 1
    thirteen = 13
    subtract = 1 

    number_gen = open('numbers.txt', 'w') 

    for number in range(one,thirteen,subtract): 
        numbers = random.randit(1,100) 
        number_gen.write(str(numbers + ' ')

    number_gen.close() 
main() 

For the second program (read)

def main(): 
    numbers_read = open('numbers.txt', 'r') 

    for line in numbers_read: 
        amount = float(line) 
        print(format(amount, '.2f'))

    numbers_read.close() 

main() 

Dani AI

Generated

Two things are going on here. The writer code in the original post has small syntax/type errors (typo in the random call and an attempt to add a string to a number), and the reader code tries to convert an entire line like "23 45 67" into a float. You need to write the numbers as tokens (space- or newline-separated) and then tokenize them when reading. , the core fix is to use random.randint and write only the string form of each number; 's suggestion to use a context manager is good because it guarantees the file is closed.

Safe, minimal writer (keeps all numbers on one line, space-separated):

import random

count = 12
with open('numbers.txt', 'w') as f:
    for i in range(count):
        f.write(str(random.randint(1, 100)))
        if i < count - 1:
            f.write(' ')
    f.write('\n')

Robust reader that prints one number per line and tolerates stray tokens:

with open('numbers.txt') as f:
    for token in f.read().split():
        try:
            x = float(token)
        except ValueError:
            continue
        print(f"{x:.2f}")   # if using Python <3.6, use "{:.2f}".format(x)

Extra tips: prefer clear names (e.g., count = 12) instead of one, thirteen, subtract; use with for file I/O; str.split() handles any whitespace so your reader works whether numbers are space- or newline-separated; add random.seed(...) if reproducible output is desired; and if the file may contain non-numeric text, re.findall(r'[-+]?\d*\.?\d+|\d+', text) can extract numeric tokens before conversion.

Don't call both function main,use name that make sense.

import random

def generate_numbers():
    one = 1
    thirteen = 13
    subtract = 1
    number_gen = open('numbers.txt', 'w')
    for number in range(one,thirteen,subtract):
        numbers = random.randint(1,100)
        number_gen.write(str(numbers) + ' ')
    number_gen.close()

def read_numers(numb):
    numbers_read = open(numb)
    numbers = [float(n) for n in numbers_read.read().split()]
    numbers_read.close()
    for n in numbers:
        print(n)

generate_numbers()
numb = 'numbers.txt'
read_numers(numb)

A more pythonic approch.

def generate_numbers():
    with open('numbers.txt', 'w') as f_out:
        f_out.write(' '.join(str(random.randint(1,100)) for i in range(12)))

def read_numers(numb):
    with open(numb) as f:
        numbers = [float(n) for n in f.read().split()]
        for n in numbers:
            print(n)

generate_numbers()
numb = 'numbers.txt'
read_numers(numb)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.