Start New Discussion within our Software Development Community

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() 

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)
This question has already been answered. Start a new discussion instead.