I have a .txt file(TB1.txt):
Monday: 12,34,-90
Saturday: 32,-23,20
I know how to read the file, but don’t know how to calculate the sum of those values in the .txt file.
#Result={}
file=open('TB1.txt','r')
line1=file.readline()
file.close()
try:
for i in line1:
i+=line1
except ValueError:
pass
print(i)
#print(Result)
I tried read the file, it could read the monday and saturday separatrly. But I don’t how to calculate when it included a str and num in a line.
I want to calculate the sum of monday and saturday separately. THX
>Solution :
To calculate the sum of the values, you need to split each line. First, separate the weekday from the values. Looks like there is a colon between them, so you could split on that. Then split the part on the right side of the colon at the commas, which seem to separate your values. Then convert the values to ints and add them up:
with open('TB1.txt', 'r') as file:
for line in file:
label, fields = line.split(':')
values = fields.split(',')
sum = 0
for v in (values):
sum += int(v)
print(f"{label}: {sum}")
This also uses with for reading the file, so that it gets automatically closed when done or in case of errors. This is not terribly important in such a small program, but it’s good style. The code also loops over all lines in the file, where yours only worked on the first line.