Python-将逗号分隔的文件读入数组

时间:2018-09-12 16:27:28

标签: 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)

1 个答案:

答案 0 :(得分:0)

我认为这与您要查找的内容相似。 (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