首页 > 解决方案 > Python - 将逗号分隔的文件读入数组

问题描述

我想读取一个包含数据的文件:

    IAGE0,IAGE5,IAGE15,IAGE25,IAGE35,IAGE45,IAGE55
    5,5,5.4,4.2,3.8,3.8,3.8
    4.3,4.3,4.9,3.4,3,3.7,3.7
    3.6,3.6,4.2,2.9,2.7,3.5,3.5
    3,3,3.6,2.7,2.7,3.3,3.3
    2.7,2.7,3.2,2.6,2.8,3.1,3.1
    2.4,2.4,3,2.6,2.9,3,3

所以我想要一个数组“iage0[1]”来读取“5”和“iage15[1]=5.4”。可以跳过标题。然后 iage0[2] = 4.3 等...对于每一行。所以一个数组是只是一列。

我认为“f.readlines(3)”会读取第 3 行,但它似乎仍然读取第一行。不知何故,我需要将该行拆分为单独的值。

这是我的代码,我不知道如何拆分“内容”或阅读下一行。很抱歉这个简单的问题,但我昨天才开始编码。

def ReadTxtFile():
    with open("c:\\jeff\\vba\\lapseC2.csv", "r") as f:
        content = f.readlines(3)
# you may also want to remove whitespace characters like `\n` 
    content = [x.strip() for x in content] 
    print("Done")
    print(content)

标签: python

解决方案


我认为这与您正在寻找的相似。(Python 3.6)

import csv

d = {}
headers = []
with open('data.csv') as file_obj:
    reader = csv.reader(file_obj)
    for header in next(reader):
        headers.append(header)
        d[header] = []
    for line in reader:
        for idx,element in enumerate(line):
            d[headers[idx]].append(element)

print(d)
{'IAGE0': ['5', '4.3', '3.6', '3', '2.7', '2.4'], 'IAGE5': ['5', '4.3', '3.6', '3', '2.7', '2.4'], 'IAGE15': ['5.4', '4.9', '4.2', '3.6', '3.2', '3'], 'IAGE25': ['4.2', '3.4', '2.9', '2.7', '2.6', '2.6'], 'IAGE35': ['3.8', '3', '2.7', '2.7', '2.8', '2.9'], 'IAGE45': ['3.8', '3.7', '3.5', '3.3', '3.1', '3'], 'IAGE55': ['3.8', '3.7', '3.5', '3.3', '3.1', '3']}
print(d['IAGE0'][0])
5
print(d['IAGE15'][0])
5.4

您还可以使用 DictReader

d = {}
headers = []
with open('data.csv') as file_obj:
    reader = csv.DictReader(file_obj)
    for line in reader:
        for key,value in line.items():
            if key not in d:
                d[key] = [value]
            else:
                d[key].append(value)


print(d)
{'IAGE0': ['5', '4.3', '3.6', '3', '2.7', '2.4'], 'IAGE5': ['5', '4.3', '3.6', '3', '2.7', '2.4'], 'IAGE15': ['5.4', '4.9', '4.2', '3.6', '3.2', '3'], 'IAGE25': ['4.2', '3.4', '2.9', '2.7', '2.6', '2.6'], 'IAGE35': ['3.8', '3', '2.7', '2.7', '2.8', '2.9'], 'IAGE45': ['3.8', '3.7', '3.5', '3.3', '3.1', '3'], 'IAGE55': ['3.8', '3.7', '3.5', '3.3', '3.1', '3']}
print(d['IAGE0'][0])
5
print(d['IAGE15'][0])
5.4

推荐阅读