Problem with sum of values from .txt file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Problem with sum of values from .txt file (/thread-15193.html) |
Problem with sum of values from .txt file - PathhK - Jan-07-2019 Hi My task is to count difference between max and min value in each lines from .txt file then sum all these values. I've done the first part(the code below) but I don't know how best is it to sum all these values(I tried many ways). I'll be grateful for help filepath = 'rows.txt' with open(filepath) as fp: line = [int(num) for num in fp.readline().split()] cnt = 1 while line: x=max(line)-min(line) print("The difference between max-min value in line",cnt,"is :",x) cnt += 1 #print(sum(x)) #print(cnt) line = [int(num) for num in fp.readline().split()]The result of this code:
RE: Problem with sum of values from .txt file - buran - Jan-07-2019 (Jan-07-2019, 07:11 PM)PathhK Wrote: I tried many waysSo, what did you tried? Post your best attempt RE: Problem with sum of values from .txt file - nilamo - Jan-07-2019 line is a list of the ints in the line. So if you create a new variable, maybe total outside the while loop, you can do: total += sum(line) .Also, why are you using a while loop? Iterating over the file directly is cleaner: with open("thefile") as fp: total = 0 for cnt, line in enumerate(fp): nums = [int(num) for num in line.split()] total += sum(nums) diff = max(nums) - min(nums) print(f"The difference between max-min value in line {cnt} is: {diff}") print(f"The total is : {total}") |