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?