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

2024-09-30 02:15:19 发布

您现在位置: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)

Tags: 文件数据代码数组contentprintreadlinesiage5
1条回答
网友
1楼 · 发布于 2024-09-30 02:15:19

我想这和你要找的差不多。(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

相关问题 更多 >

    热门问题