help with this basic script for adding contents of a csv col

This is the place for queries that don't fit in any of the other categories.

help with this basic script for adding contents of a csv col

Postby yoyo » Tue Dec 10, 2013 8:44 pm

Im trying to get this code to: prompt user to specify a csv file and column number , add the contents of the column and get the mean , print out the results.

Code: Select all
 #!/bin/env python
import csv
import sys

if len(sys.argv) < 3:
    print('Please specify a filename and column number: {} [csvfile] [column]'.format(sys.argv[0]))
    sys.exit(1)

filename = sys.argv[1]
column = int(sys.argv[2])

for line in filename() , column ():
    elements = line.strip().split(',')
    values.append(int(elements[col]))

csum = sum(values)
cavg = sum(values)/len(values)
print("Sum of column %d: %f" % (col, csum))
print("Avg of column %d: %f" % (col, cavg))
Last edited by stranac on Tue Dec 10, 2013 8:53 pm, edited 1 time in total.
Reason: First post lock.
yoyo
 
Posts: 2
Joined: Tue Dec 10, 2013 8:35 pm

Re: help with this basic script for adding contents of a csv

Postby tnknepp » Tue Dec 10, 2013 9:22 pm

yoyo wrote:Im trying to get this code to: prompt user to specify a csv file and column number , add the contents of the column and get the mean , print out the results.


A worthy endeavor...but what is the problem?
Python: 2.7 via Anaconda
Numpy: 1.7
Pandas: 0.11
OS: Windows 7
IDE: Spyder/IPython
User avatar
tnknepp
 
Posts: 119
Joined: Mon Mar 11, 2013 7:41 pm

Re: help with this basic script for adding contents of a csv

Postby yoyo » Tue Dec 10, 2013 9:45 pm

im getting this
error or line in filename() , column ():
TypeError: 'str' object is not callable

works ok then i add this , but dont want to keep changing the col and filename every time i run the program on different csv files.
Code: Select all
 col = 2

values = []
with open('test.csv', 'r') as csv:
for line in csv.readlines():
    elements = line.strip().split(',')
    values.append(int(elements[col]))
yoyo
 
Posts: 2
Joined: Tue Dec 10, 2013 8:35 pm

Re: help with this basic script for adding contents of a csv

Postby Kebap » Tue Dec 10, 2013 11:11 pm

Your problem is not whether you say col = 2 or not, but in the line where your for loop starts. See the difference?

Please post the whole error messages in the future, they show the exact line involved and which error is happening.
Learn: How To Ask Questions The Smart Way
Join the #python-forum IRC channel on irc.freenode.net and chat with uns directly!
Kebap
 
Posts: 394
Joined: Thu Apr 04, 2013 1:17 pm
Location: Germany, Europe


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests