I need to write a program, in Python, that looks at a list of numbers in a separate text file, and does the following: Displays all the numbers from the file, adds the total of all the numbers, tells me how many numbers are in the file. My problem is that it skips the first number in file
Here's the code for the program that's writing to the file, if that helps at all:
import random
amount = int (input ('How many random numbers do you want in the file? '))
infile = open ('random_numbers.txt', 'w')
for x in range (amount):
numbers = random.randint (1, 500)
infile.write (str (numbers) + '\n')
infile.close()
And here's my code for the reading the numbers in the file:
amount = 0
total = 0
infile = open ('random_numbers.txt', 'r')
numbers = (infile.readline())
try:
while numbers:
numbers = (infile.readline())
numbers = numbers.strip('\n')
numbers = int (numbers)
print (numbers)
total += numbers
amount += 1
except ValueError:
pass
print ('')
print ('')
amount +=1
print ('Your total is: ' ,total)
print ('The amount of numbers in file is: ', amount)
Now my issue is that it skips over the first number in the file. I first noticed it wasnt giving me the correct amount of numbers, hence the additional statement to add an additional 1 to the amount variable. But then I tested again and noticed it was skipping the first number in file.
How about:
with open('random_numbers.txt', 'r') as f:
numbers = map(lambda x: int(x.rstrip()), f.readlines())
This strips any trailing newline characters from the line in the string and then casts it as an int. It also closes the file when done with it.
I'm not sure why you'd want to count how many times it loops, but if that's what you want to do, you can do it this way:
numbers = list()
with open('random_numbers.txt', 'r') as f:
counter = 0
for line in f.readlines():
try:
numbers.append(int(line.rstrip()))
except ValueError: # Just in case line can't be converted to int
pass
counter += 1
I would just use len(numbers)
with the result of the first method, though.
As ksai mentioned, the ValueError
is coming up, most likely, because of the \n
at the end of the line. I've added an example of catching the ValueError with a try/except
just in case it comes across a line that's not convertible to a number for some reason.
Here's the code successfully running in my shell:
In [48]: import random
...:
...: amount = int (input ('How many random numbers do you want in the file?
...: '))
...: infile = open ('random_numbers.txt', 'w')
...: for x in range (amount):
...: numbers = random.randint (1, 500)
...: infile.write (str (numbers) + '\n')
...: infile.close()
...:
How many random numbers do you want in the file? 5
In [49]: with open('random_numbers.txt', 'r') as f:
...: numbers = f.readlines()
...: numbers = map(lambda x: int(x.rstrip()), numbers)
...:
In [50]: numbers
Out[50]: <map at 0x7f65f996b4e0>
In [51]: list(numbers)
Out[51]: [390, 363, 117, 441, 323]