Reputation: 15
I'm new to python and I was trying to take data from a file, put it into a list and then get the sum of each line. I tried stripping the list for anything but int's and floats and made sure the file only had numbers. If anyone could help me I would be very greatful. Thanks for reading
(Problem code)
with open("InputFileData.csv") as file:
SampleTotalHours = file.readlines();
TotalHours = []
for element in SampleTotalHours:
TotalHours.append(element.strip())
Sum = sum(TotalHours[0])
print(Sum)
(contents "InputFileData.csv")
40.1,39.7,40,38
36,36,35.5,35.8
40,41.6,40.3,40
20.4,22.8,20,20
(Output)
Traceback (most recent call last):
File "D:\Assignment 6 Files\PAtest.py", line 10, in <module>
Sum = sum(TotalHours[0])
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Upvotes: 0
Views: 92
Reputation: 177991
Here's some popular libraries to look over (first built-in, the other 3rd party):
import csv
with open('InputFileData.csv', newline='') as file:
reader = csv.reader(file,quoting=csv.QUOTE_NONNUMERIC)
for row in reader:
print(row,sum(row))
Output:
[40.1, 39.7, 40.0, 38.0] 157.8
[36.0, 36.0, 35.5, 35.8] 143.3
[40.0, 41.6, 40.3, 40.0] 161.89999999999998
[20.4, 22.8, 20.0, 20.0] 83.2
import pandas as pd
df = pd.read_csv('InputFileData.csv',header=None)
df['Sum'] = df.sum(axis=1)
print(df)
Output:
0 1 2 3 Sum
0 40.1 39.7 40.0 38.0 157.8
1 36.0 36.0 35.5 35.8 143.3
2 40.0 41.6 40.3 40.0 161.9
3 20.4 22.8 20.0 20.0 83.2
Upvotes: 0
Reputation: 134
This work for me fine:
TotalHours = 0
with open("InputFileData.csv") as file:
for line in file:
for number in line.strip().split(","):
if number.replace('.', "").isnumeric():
TotalHours += float(number)
print(TotalHours)
Upvotes: 0
Reputation: 116
readlines()
will return a list of strings, the first item in this case being "40.1,39.7,40,38".
To get the sum, you'll need to first split the string by the delimiter and cast each value to a float before taking their sum.
TotalHours = []
for element in SampleTotalHours:
hoursAsStrings = element.split(',')
hoursAsFloats = [float(hourString) for hourString in hoursAsStrings]
TotalHours.append(sum(hoursAsFloats))
TotalHours
is a list where each value is the sum of its corresponding row.
Upvotes: 2
Reputation: 54757
Kind of like this. For each line, split it at the commas, convert the fields to floats, sum the floats. You might find it easier using the csv
module, but it doesn't really gain you much with this data set.
TotalHours = []
with open("InputFileData.csv") as file:
for line in file:
parts = [float(k) for k in line.strip().split(',')]
TotalHours.append( sum(parts) )
print(TotalHours)
Upvotes: 0