adding values from a csv column and getting the mean. beginner help

Tim Chase python.list at tim.thechases.com
Wed Dec 11 14:20:27 EST 2013


On 2013-12-11 11:10, brian cleere wrote:
> filename = sys.argv[1]
> column = int(sys.argv[2])
> 
> for line in filename() , column ():
>     elements = line.strip().split(',')
>     values.append(int(elements[col]))

1) you need to open the file

2) you need to make use of the csv module on that file

3) you need to extract the column

Thus it would looks something like

  column = int(sys.argv[2])
  f = open(sys.argv[1], "rb")
  r = csv.reader(f)
  try:
    for row in r:
      values.append(int(row[column]))
  finally:
    f.close()

which can be obtusely written as

  values = [int(row[column]) for row in csv.reader(open(sys.argv[1], "rb"))]

though the more expanded version allows you to do better error
handling (rows with insufficient columns, non-numeric/non-integer
values in the specified column, etc).

-tkc






More information about the Python-list mailing list