2017-05-15 54 views
0

我試圖導入CSV文件到python,但我希望所有列都作爲變量單獨導入,下面的代碼只導入一列。我怎樣才能做到這一點所有列?如何在Python中分別導入每個CSV列

import csv 

import operator 

import math 

f = open('/Users/Maria/Downloads/CSV/proses110.csv') 
csv_f = csv.reader(f) 

SetDryTemp = [] 

for row in csv_f: 
    row_int = int(row[2]) 
    SetDryTemp.append(row_int) 

print SetDryTemp[0] 


import csv 

l = open('/Users/Maria/Downloads/CSV/proses102.csv') 
csv_l = csv.reader(l) 

SetDryTemp2 = [] 

for row in csv_l: 
    row_int2 = int(row[2]) 
    SetDryTemp2.append(row_int2) 

print SetDryTemp2[0] 

回答

0

考慮保存所有行到一個列表,然後解壓縮到單獨的變量與zip(*mylist)

import csv 

SetDryTemp1 = []; SetDryTemp2 = [] 

with open('/path/to/csv1.csv') as f1, open('path/to/csv2.csv') as f2: 
    csv_f1 = csv.reader(f1); csv_f2 = csv.reader(f2) 
    for row in csv_f1: 
     # APPENDS FIRST THREE COLUMNS (ADJUST COL INDEX AS NEEDED) 
     SetDryTemp1.append([row[0], row[1], int(row[2])]) 

    for row in csv_f2: 
     # APPENDS FIRST THREE COLUMNS (ADJUST COL INDEX AS NEEDED) 
     SetDryTemp2.append([row[0], row[1], int(row[2])]) 

SetDryTemp1_Col1, SetDryTemp1_Col2, SetDryTemp1_Col3 = zip(*SetDryTemp1) 
SetDryTemp2_Col1, SetDryTemp2_Col2, SetDryTemp2_Col3 = zip(*SetDryTemp2) 
+0

感謝您的回覆, –

+0

其實我用餘弦相似度這個代碼,所以現在我得到這樣的錯誤:類型錯誤:不能通過'tuple'類型的非整型來乘序列 –