RevvedUp
RevvedUp

Reputation: 23

Python write random integers to file on newline

I need to make a program that generates 10 random integers between 10 and 90 and calls two separate functions to perform separate actions. The first one (playlist) simply needs to print them all on one line without spaces, which was easy. The second one (savelist) is giving me problems. I need to write every number in the list nums to angles.txt with each number on a separate line in order. No matter what I try I can't get them on separate lines and it appears as one string on a single line. What am I missing?

import random

def main():
    nums = []
    # Creates empty list 'nums'
    for n in range(10):
        number = random.randint(10, 90)
        nums.append(number)
        # Adds 10 random integers to list
    playlist(nums)
    savelist(nums)

def playlist(numb):
    index = 0
    while index < len(numb):
        print(numb[index], end=' ')
        index += 1

def savelist(number):
    myfile = open('angles.txt', 'w')
    # Creates numbers.txt file
    number.sort()
    myfile.write(str(number) + '\n')
    myfile.close()

main()

Upvotes: 2

Views: 2007

Answers (5)

Hugh Bothwell
Hugh Bothwell

Reputation: 56644

Here's how I would do it:

from random import randint

def rand_lst(lo, hi, how_many):
    return [randint(lo, hi) for _ in range(how_many)]

def print_lst(nums):
    print(''.join(str(num) for num in nums))

def save_lst(nums, fname):
    with open(fname, "w") as outf:
        outf.write('\n'.join(str(num) for num in sorted(nums)))

def main():
    nums = rand_lst(10, 90, 10)
    print_lst(nums)
    save_lst(nums, "angles.txt")

if __name__ == "__main__":
    main()

Upvotes: 0

Thomas Lester
Thomas Lester

Reputation: 192

In savelist(), you need to loop through the list:

myfile = open('angles.txt', 'w')
# Creates numbers.txt file

number.sort()

for e in number:
  myfile.write(str(e))

myfile.close()

When you send "nums" to savelist(), you are sending a list. If you just try to write "numbers" to the file, it's going to write the whole list. So, by looping through each element in the list, you can write each line to the file.

Upvotes: 1

Paul Rooney
Paul Rooney

Reputation: 21609

@tomlester already stated that you need to loop through the elements in number. Another way to do this is.

def savelist(number):

    number.sort()
    with open('angles.txt', 'w') as myfile:
        myfile.write('\n'.join(map(str, number)))

Upvotes: 0

mfitzp
mfitzp

Reputation: 15545

To write a list to a file you need to iterate over each element of the list and write it individually, with the attached newline. For example:

def savelist(number):

    myfile = open('angles.txt', 'w')
    # Creates numbers.txt file

    number.sort()

    for n in number:
        myfile.write(str(number) + '\n')

    myfile.close()

You could also generate a single string by joining your list with newlines, and then write that to the file. For example:

    myfile.write('\n'.join([str(n) for n in number])

Finally, you may want to consider using a context manager on the file open, to ensure that the file is closed whatever happens. For example:

def savelist(nums):

    # Creates numbers.txt file
    nums.sort()

    with open('angles.txt', 'w') as myfile:
        myfile.write('\n'.join([str(n) for n in nums])

Note that I also changed the variable name to nums rather than number ('number' is slightly confusing, since the list contains >1 number!).

Upvotes: 1

deltashade
deltashade

Reputation: 386

Try this code out: You are writing an array as a whole to the file, and therefore are seeing only one line.

def main():
nums = [] # Creates empty list 'nums'

for n in range(10):
    number = random.randint(10, 90)
    nums.append(number)
    # Adds 10 random integers to list

playlist(nums)

savelist(nums)


def playlist(numb):
    index = 0

    while index < len(numb):
        print(numb[index], end=' ')
        index += 1

def savelist(number):
    myfile = open('angles.txt', 'w')
    # Creates numbers.txt file

    number.sort()
    for element in number:
       myfile.write(str(element) + '\n')

    myfile.close()

main()

Upvotes: 0

Related Questions