阅读.csv文件,Python和DictReader缺少列

chhqkbe1  于 2022-12-30  发布在  Python
关注(0)|答案(2)|浏览(149)

我有下面的.csv文件,我试图作为一个整体阅读:

---------------------------------------------------------------
#INFO            |           |        |       |        |      |
---------------------------------------------------------------
#Study name      | g1        |        |       |        |      |
---------------------------------------------------------------
#Respondent Name | name      |        |       |        |      |
---------------------------------------------------------------
#Respondent Age  | 20        |        |       |        |      |
---------------------------------------------------------------
#DATA            |           |        |       |        |      |
---------------------------------------------------------------
Row              | Timestamp | Source | Event | Sample | Anger|
---------------------------------------------------------------
1                | 133       | Face   | 1     | 3      | 0.44 |
---------------------------------------------------------------
2                | 240       | Face   | 1     | 4      | 0.20 |
---------------------------------------------------------------
3                | 12        | Face   | 1     | 5      | 0.13 |
---------------------------------------------------------------
4                | 133       | Face   | 1     | 6      | 0.75 |
---------------------------------------------------------------
5                | 87        | Face   | 1     | 7      | 0.25 |
---------------------------------------------------------------

Image of the file
下面是我用来打开、读取文件和打印到终端的代码:

import csv

def read_csv():
    with open("in/2.csv", encoding="utf-8-sig") as f:
        reader = csv.DictReader(f)
        print(list(reader))
read_csv()

我得到的输出只包括.csv的前两列:

[{'#INFO': '#Study name', '': ''}, {'#INFO': '#Respondent Name', '': ''}, {'#INFO': '#Respondent Age', '': ''}, {'#INFO': '#DATA', '': ''}, {'#INFO': 'Row', '': 'Anger'}, {'#INFO': '1', '': '4.40E-01'}, {'#INFO': '2', '': '2.00E-01'}, {'#INFO': '3', '': '1.30E-01'}, {'#INFO': '4', '': '7.50E-01'}, {'#INFO': '5', '': '2.50E-01'}]

为什么我的输出中缺少其他列?我希望从Row开始的其他列也包括在内。任何方向都将受到赞赏。谢谢!

cbeh67ev

cbeh67ev1#

DictReader要求文件的第一行包含列名(每个列名彼此不同),后续行包含数据条目。如果多个列名只是空字符串,则最后一列中的值将被分配给返回字典中的键''
要跳过前五行,您可以这样写:

import csv

def read_csv():
    with open("in/2.csv", encoding="utf-8-sig") as f:
        for _ in range(5):
            next(f)

        reader = csv.DictReader(f)
        print(list(reader))
read_csv()
nr9pn0ug

nr9pn0ug2#

试试看:

for _ in zip(f, range(5)): 
    pass

在初始化DictReader之前。这应该跳过前5行。

import csv

def read_csv():
    with open("in/2.csv", encoding="utf-8-sig") as f:
        for _ in zip(f, range(5)): 
            pass
        reader = csv.DictReader(f)
        print(list(reader))
read_csv()

相关问题