2017-09-11 10 views
-1

私は.csvファイルからデータを読み込み、それを使ってデータの数学的計算を行うPythonスクリプトを用意しています。私はそれを実行すると、私はこのエラーを取得:TypeError:Unicodeに強制する: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 

私のコードは次のようになります。計算機能で

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 

、その過去のすべてがちょうど任意の数学です。

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

答えて

2
with open(file 

あなたのスペルミスdataFile:よう

私の主なルックス。

fileは、ファイルオブジェクト用の組み込みPythonデータ型です。誤って型を開こうとしています。

+0

これは間違いありません、ありがとうございます!私はとても混乱しましたが、今は完全に動作します –

関連する問題