简体   繁体   English

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

[英]Python - read comma delimited file into array

I want to read a file that has data: 我想读取一个包含数据的文件:

    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

So I want an array "iage0[1]" to read "5 and "iage15[1]=5.4". The header can be skipped. Then iage0[2] = 4.3 etc... for each row. So an array is just a column. 因此,我希望数组“ iage0 [1]”读取为“ 5,并且“ iage15 [1] = 5.4”。可以跳过标题。然后每一行的iage0 [2] = 4.3等...所以一个数组是只是一列。

I thought "f.readlines(3)" would read line 3, but it seems to still read the first line. 我以为“ f.readlines(3)”将读取第3行,但似乎仍读取第一行。 Somehow I need to split the line into separate values. 我需要以某种方式将行拆分为单独的值。

Here is my code, I don't know how to split up the "content" or read the next line. 这是我的代码,我不知道如何拆分“内容”或阅读下一行。 Sorry for the simple question but I just started coding yesterday. 很抱歉这个简单的问题,但是我昨天才开始编码。

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)

I assume this is similar to what you're looking for. 我认为这与您要查找的内容相似。 (Python 3.6) (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

You can also use DictReader 您也可以使用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

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

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