1

I want to sum all of the number in the file. I wrote two solutions to solve the problem like below.

import sys
import re

if len(sys.argv) != 2:
    print("Need 2 parameters!")
    quit(2)    # 2 for command line error
    # 0 for normal quit
    # 1 for all other kinds of error

if sys.argv[1] == "sample" :
    f = open("regex_sum_42.txt", "r")
else:
    f = open("regex_sum_89382.txt", "r")

#Solution1:

total = 0
for line in f :
    line_num = re.findall("[0-9]+", line)
    total = total + sum([int(each) for each in line_num])

print(total)
print("******************")
print(f.read())

#Solution2:
print(sum([int(each) for each in re.findall( "[0-9]+" ,f.read())]))

I thought the output is

511355
******************
(something that is file content)
511355

However, the output is

511355
******************

0

I make sure that both of the two solutions are right. Since the output is 511355 if I run the two solution individually.

But, when I run them together, the result of solution 2 is 0. I tried to print the f after solution 1 and it is nothing. Does somebody know why?

Chris
  • 67
  • 6
  • 1
    You read the entire file in that `for line in f:` loop. And then you read the rest of the file with `f.read()`. Since you already read the whole thing, the rest of the file is nothing. – abarnert Apr 07 '18 at 20:57
  • 1
    This is definitely a dup of a question that has a nicely detailed answer; I'll go find one. – abarnert Apr 07 '18 at 20:58
  • Either rewind the file using `f.seek(0)` or close then open the file again. – cdarke Apr 07 '18 at 21:00
  • 1
    If none of those answers explain it well enough, see [this one](https://stackoverflow.com/questions/3906137/why-cant-i-call-read-twice-on-an-open-file), [this one](https://stackoverflow.com/questions/11150155/why-cant-i-repeat-the-for-loop-for-csv-reader-python), and [this one](https://stackoverflow.com/questions/36572993/python-the-second-for-loop-is-not-running). Between them they cover all of the options (read the lines into a list, close and re-open the file, seek to 0, …). – abarnert Apr 07 '18 at 21:01
  • Thank both of you. I got what is happening. – Chris Apr 07 '18 at 22:18

0 Answers0