简体   繁体   English

在Python中制作CSV列表

[英]Making a CSV list in Python

I am new to python and need help. 我是python新手,需要帮助。 I am trying to make a list of comma separated values. 我正在尝试列出用逗号分隔的值。 I have this data. 我有这个数据。

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 

Now how do I get something like this; 现在我如何得到这样的东西;

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

and so on?? 等等??

So far I have been able to do this: 到目前为止,我已经能够做到这一点:

 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

Use the csv module 使用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 is a text file containing: 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 

Output: 输出:

{'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', '']}

Try this: 尝试这个:

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

Running it: 运行它:

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

Result: 结果:

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']

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

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