0

basically i'm trying to complete a read file. i have made the "make" file that will generate 10 random numbers and write it to a text file. here's what i have so far for the "read" file...

def main():
    infile = open('mynumbers.txt', 'r')
    nums = []
    line = infile.readline()

    print ('The random numbers were:')
    while line:
        nums.append(int(line))
        print (line)
        line = infile.readline()

    total = sum(line)  
    print ('The total of the random numbers is:', total)

main()

i know it's incomplete, i'm still a beginner at this and this is my first introduction to computer programming or python. basically i have to use a loop to gather up the sum of all the numbers that were listed in the mynumbers.txt. any help would be GREATLY appreciated. this has been driving me up a wall.

1
  • He/she's a beginner guys, please cut them some slack! Commented Feb 27, 2014 at 5:44

3 Answers 3

2

You don't need to iterate manually in Python (this isn't C, after all):

nums = []
with open("mynumbers.txt") as infile:
    for line in infile:
        nums.append(int(line))

Now you just have to take the sum, but of nums, of course, not of line:

total = sum(nums)
Sign up to request clarification or add additional context in comments.

1 Comment

typo: infile vs file. Instead of appending to a list you could just add the newly read integer to a total variable that was initialized to zero.
1

The usual one-liner:

total = sum(map(int, open("mynumbers.txt")))

It does generate a list of integers (albeit very temporarily).

1 Comment

He's on Python 3, so it doesn't even generate a list - this is definitely the most elegant solution (+1), although it's probably a bit much for a beginner, especially without explanation.
0

Although I would go with Tim's answer above, here's another way if you want to use readlines method

# Open a file
infile = open('mynumbers.txt', 'r')

sum = 0
lines = infile.readlines()
for num in lines:
    sum += int(num)

print sum

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.