在Python中创建CSV列表

时间:2013-07-10 11:27:10

标签: python csv python-2.7

我是python的新手,需要帮助。我正在尝试列出逗号分隔值。 我有这些数据。

EasternMountain 84,844 39,754 24,509 286 16,571 3,409 315 
EasternHill 346,373 166,917 86,493 1,573 66,123 23,924 1,343 
EasternTerai 799,526 576,181 206,807 2,715 6,636 1,973 5,214 
CentralMountain 122,034 103,137 13,047 8 2,819 2,462 561 

现在我怎么得到这样的东西;

"EasternMountain": 84844,
"EasternHill":346373,

等等?

到目前为止,我已经能够做到这一点:

 fileHandle = open("testData", "r")
 data = fileHandle.readlines()
 fileHandle.close()

 dataDict = {}

 for i in data:
    temp = i.split(" ")

    dataDict[temp[0]]=temp[1]
    with_comma='"'+temp[0]+'"'+':'+temp[1]+','
    print with_comma

2 个答案:

答案 0 :(得分:3)

使用csv模块

import csv
with open('k.csv', 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ')
    my_dict = {}
    for row in reader:
        my_dict[row[0]] = [''.join(e.split(',')) for e in row[1:]]

print my_dict

k.csv是一个包含以下内容的文本文件:

EasternMountain 84,844 39,754 24,509 286 16,571 3,409 315 
EasternHill 346,373 166,917 86,493 1,573 66,123 23,924 1,343 
EasternTerai 799,526 576,181 206,807 2,715 6,636 1,973 5,214 
CentralMountain 122,034 103,137 13,047 8 2,819 2,462 561 

<强>输出:

{'EasternHill': ['346373', '166917', '86493', '1573', '66123', '23924', '1343', ''], 'EasternTerai': ['799526', '576181', '206807', '2715', '6636', '1973', '5214', ''], 'CentralMountain': ['122034', '103137', '13047', '8', '2819', '2462', '561', ''], 'EasternMountain': ['84844', '39754', '24509', '286', '16571', '3409', '315', '']}

答案 1 :(得分:0)

试试这个:

def parser(file_path):
    d = {}
    with open(file_path) as f:
        for line in f:
            if not line:
                continue
            parts = line.split()
            d[parts[0]] = [part.replace(',', '') for part in parts[1:]]
    return d

运行它:

result = parser("testData")
for key, value in result.items():
    print key, ':', value

结果:

EasternHill : ['346373', '166917', '86493', '1573', '66123', '23924', '1343']
EasternTerai : ['799526', '576181', '206807', '2715', '6636', '1973', '5214']
CentralMountain : ['122034', '103137', '13047', '8', '2819', '2462', '561']
EasternMountain : ['84844', '39754', '24509', '286', '16571', '3409', '315']