Reputation: 3
I have started learning python with great enthusiasm and managed to get through the procedures, functions and bit of lists. And feel ready to take the learning forward by building a useful application.
I would like the user to export an excel file into csv with just one row of numbers, some of them negative, positive and zeros. And want to calculate the average of positive numbers and average of negative numbers.
The calculating bit isn't the problem, its the importing csv bit. I've been reading the python documentation but looked confusing.
Please get me started on importing a csv file and summing the row of numbers. Thank you!
Upvotes: 0
Views: 6833
Reputation: 34438
This should get you started.
import csv
with open("file.csv", "rb") as ins:
for row in csv.reader(ins):
print sum(map(int, row))
The with statement is a way to make this exception-safe. In most cases, the following is good enough:
import csv
ins = open("file.csv", "rb")
for row in csv.reader(ins):
print sum(map(int, row))
ins.close()
The above solutions don't work with Python 3. Instead, try this:
import csv
with open("test.csv", "r") as ins:
for row in csv.reader(ins):
print(sum(map(int, row)))
Upvotes: 3