0

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.

Whitekong
  • 21
  • 1
  • 5
  • It could be because of while writing in the file you added `'\n'` at the end of line, now at the time of reading you converting `'\n'` to `int` which is not possible – ksai Jul 30 '17 at 03:47
  • @ksai I'm pretty sure that's right actually. I've attempted stripping the \n from it, to no avail. – Whitekong Jul 30 '17 at 03:53

5 Answers5

2

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]
Cory Madden
  • 5,026
  • 24
  • 37
0

Assuming, as in your code that generates these numbers, that the contents of 'random_numbers.txt' are integers separated by newlines:

with open('random_numbers.txt', 'r') as f:
    numbers = [int(line) for line in f.readlines()]
    total = sum(numbers)
    numOfNums = len(numbers)

'numbers' contains all the numbers from the file in a list. You can print this or print(','.join(map(str,numbers))) if you don't want the square brackets.

'total' is their sum

'numOfNums' is how many numbers were in the file.

Andrew Lei
  • 335
  • 2
  • 9
0

What ended up working for me was this:

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)

Cory's tip on adding a try and except is what I believe ended up doing the trick.

Whitekong
  • 21
  • 1
  • 5
  • nevermind, now it's having an issue of skipping over the first number in the file – Whitekong Jul 30 '17 at 04:18
  • It's skipping over the first number because you're immediately overwriting it in the first line of your `while` statement. I'd also put the `try/except` in the `while` loop so that it doesn't stop on the first bad line. – Cory Madden Jul 30 '17 at 04:23
  • How would I get around overwriting it? – Whitekong Jul 30 '17 at 04:27
  • Move `numbers = (infile.readline())` to the end of the loop after you're done working on it. Yea, I just tested with your code and it worked fine. – Cory Madden Jul 30 '17 at 04:29
  • Thanks! Huge help man. Hopefully I can use all this for this other program I'm writing as well. – Whitekong Jul 30 '17 at 04:34
0

If me, I would like to code like this:

from random import randint

fname = 'random_numbers.txt'
amount = int(input('How many random numbers do you want in the file? '))
with open(fname, 'w') as f:
    f.write('\n'.join([str(randint(1, 500)) for _ in range(amount)]))

with open(fname) as f:
    s = f.read().strip()    
numbers = [int(i) for i in s.split('\n') if i.isdigit()]
print(numbers)

Or like this (need to pip install numpy):

import numpy as np
from random import randint

fname = 'random_numbers.txt'
amount = int(input('How many random numbers do you want in the file? '))
np.array([randint(1, 500) for _ in range(amount)]).tofile(fname)

numbers = np.fromfile(fname, dtype='int').tolist()
print(numbers)
williezh
  • 917
  • 5
  • 8
0

I think the issue is how you placed the code as you unintentionally skipped the first row with another call of infile.readline()

amount = 0
total = 0
infile = open ('random_numbers.txt', 'r')
numbers = (infile.readline())
try:

    while numbers:
        numbers = numbers.strip('\n')
        numbers = int (numbers)
        print (numbers)
        total += numbers
        amount += 1
        numbers = (infile.readline())       #Move the callback here. 


except ValueError:
    raise ValueError
print ('')
print ('')
# The amount should be correct already, no need to increment by 1.
# amount +=1

print ('Your total is: ' ,total)
print ('The amount of numbers in file is: ', amount)

Works fine for me.

Khanh Nguyen
  • 101
  • 4