如何在python

时间:2017-05-15 13:02:37

标签: python csv import python-import

我曾尝试将CS​​V文件导入python,但我希望将所有列作为变量单独导入,下面的代码只导入一列。我怎样才能为所有列做到这一点?

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]

1 个答案:

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