Cassidy Haas
Cassidy Haas

Reputation: 65

TypeError: coercing to Unicode: need string or buffer, type found when running python file

I have a python script that reads in data from a .csv file and uses it to make mathematical calculation on the data. When I run it, I get this error:

Traceback (most recent call last):
  File "HW1_PythonTemplate.py", line 120, in <module>
    print ','.join(map(str,calculate(args.data, args.i)))
  File "HW1_PythonTemplate.py", line 56, in calculate
    with open(file, 'r') as csvfile:
TypeError: coercing to Unicode: need string or buffer, type found

My code looks like:

import argparse
import csv
import sys

def calculate( dataFile, ithAttr):


    numObj, minValue, maxValue, mean, stdev, Q1, median, Q3, IQR = [0,"inf","-inf",0,0,0,0,0,0]

    rows = []
    with open(file, 'r') as csvfile:
        csvreader = csv.reader(csvfile)
        for row in csvreader:
            rows.append(row)

    columniStr = [row[ithAttr-1] for row in rows]
    columniFloat = []
    for value in columniStr:
        try:
            columniFloat.append(float(value))
        except ValueError:
            pass

In the calculate function, everything past that is just arbitrary math.

My main looks like:

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='calc')
    parser.add_argument('--i', type=int,
                            help="ith attribute of the dataset (2 <= i <= 29)", 
                            default=5,
                            choices=range(2,30),
                            required=True)
    parser.add_argument("--data", type=str, 
                            help="Location of the dataset file",
                            default="energydata_complete.csv", 
                            required=True)
    args = parser.parse_args()

    print ','.join(map(str,calculate(args.data, args.i)))

Upvotes: 0

Views: 919

Answers (1)

bobince
bobince

Reputation: 536409

with open(file

You mis-spelled dataFile.

file is the built-in Python datatype for file objects, so you're accidentally trying to open a type.

Upvotes: 4

Related Questions