简体   繁体   English

从python中的csv读取列

[英]Read columns from csv in python

I have a csv file with columns id, name, address, phone. 我有一个csv文件,其中包含列ID,名称,地址,电话。 I want to read each row such that I store the data in two variables, key and data , where data contains name, address and phone. 我想读取每一行,以便将数据存储在两个变量( keydata ,其中data包含名称,地址和电话。 I want to do this because I want to append another column country in each row in a new csv. 我要这样做是因为我想在新的csv中的每行中附加另一个列国家/地区。 Can anyone help me with the code in python. 谁能帮我用python中的代码。 I tried this but it didn't work: 我试过了,但是没有用:

dict = {}
reader = csv.reader(open('info.csv', 'r'))
for row in reader:
    key, *data = row
    dict[key] = ','.join(data)

key, *data = row is Python 3 syntax. key, *data = row是Python 3语法。 For Python 2 you can do this: 对于Python 2,您可以执行以下操作:

key, data = row[0], row[1:]

You can try the code below. 您可以尝试下面的代码。 I have put two option one is to make a list for each row, and other is comma separated. 我提出了两种选择,一种是为每一行创建一个列表,另一种是用逗号分隔。 Based on the usage you can use either one. 根据用法,您可以使用其中一种。

import csv
dict = {}
reader = csv.reader(open('info.csv', 'r'))
for row in reader:
    data = []
    print row
    key,data = row[0],row[1:]
    dict[key] = data
    # dict[key] = ','.join(data)
print dict    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM