2017-06-09 91 views
0
import csv 

oneFileName = listOfFiles[0] 

lineNum = 0 

listOfLists = [] 

with open(oneFileName,"rt") as csvfile: 
    lineReader = csv.reader(csvfile,delimiter=",",quotechar="\"") 
    for row in lineReader: 
     lineNum = (lineNum + 1) 
     if lineNum == 1: 
      print("Skipping the header row") 
      continue 
     symbol = row[0] 
     close = row[5] 
     prevClose = row[7] 
     tradedQty = row[9] 
     pctChange = float(float(close)/float(prevClose) - 1) 
     oneResultRow = [symbol, pctChange,float(tradedQty)] 
     listOfLists.append(oneResultRow) 
     print(symbol, "{:,.lf}".format(float(tradedQty/1e6), "M INR", "{:,.lf}".format(pctChange*100), "%")) 
    print("Done iterating over the file contents - the file is closed now!") 
    print("We have stock info for " + str(len(listOfLists))) 

listOfListsSortedByQty = sorted(listOfLists, key=lambda x:x[2], reverse=True) 

listOfListsSortedByQty = sorted(listOfLists, key=lambda x: x[1], reverse=True) 

我不斷收到此錯誤:1e6是否會導致類型錯誤?

print(symbol, "{:,.lf}".format(float(tradedQty/1e6), "M INR", "{:,.lf}".format(pctChange*100), "%")) 
TypeError: unsupported operand type(s) for /: 'str' and 'float 

回答

0

tradedQty是一個字符串。 1e6是數字,並不是問題。

CSV文件只是字符串,所以您需要將數字數據轉換爲數字類型。嘗試tradedQty = float(row[9])

1

不,問題是你把括號放在錯誤的地方。

float(tradedQty/1e6) 
//  ^^^^^^^^^ ^^^ 
//  string float 
// ^^^^^ 
// too late 

我敢肯定你的意思是寫:

float(tradedQty)/1e6