2017-09-11 2 views
-1

J'ai un script python qui lit les données d'un fichier .csv et l'utilise pour effectuer un calcul mathématique sur les données. Quand je lance, je reçois cette erreur:TypeError: coercing to Unicode: besoin de chaîne ou de tampon, type trouvé lors de l'exécution du fichier python

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 

Mon code ressemble:

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 

Dans la fonction de calcul, tout passé qui est juste mathématiques arbitraire.

Mes principaux ressemble:

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))) 

Répondre

2
with open(file 

Vous mal orthographié dataFile. Est le type de données Python intégré pour les objets fichier, donc vous essayez accidentellement d'ouvrir un type.

+0

C'est correct, merci! J'étais tellement confus mais ça fonctionne parfaitement maintenant –