简体   繁体   English

将 csv 文件读取到字典 - 仅读取第一个键+值

[英]Reading csv file to dictionary - only reads first key+value

I have a function that reads a csv file into a dictionary but the next iterator seems to not be working since it inly reads the first pair key+value.我有一个 function 将 csv 文件读入字典,但下一个迭代器似乎不起作用,因为它只读取第一对键+值。

reader = csv.DictReader(open(folder_path+'/information.csv'))
info = next(reader)

My csv file is structured this way:我的 csv 文件的结构是这样的:

Test Name
mono1
Date
18/03/2021
Time
18:25
Camera
monochromatic

and the dictionary return is:字典返回是:

{'Test Name': 'mono1'}

Any idea of what's happening?知道发生了什么吗? Or a better way to read the file without having to change its structure?还是一种无需更改其结构即可读取文件的更好方法?

Your file is not a CSV.您的文件不是 CSV。 It would need to be structured as follows:它的结构需要如下:

Test Name,Date,Time,Camera
mono1,18/03/2021,18:25,monochromatic

Which would be read with:这将与以下内容一起阅读:

import csv

with open('test.csv',newline='') as f:
    reader = csv.DictReader(f)
    for line in reader:
        print(line)

Output: Output:

{'Test Name': 'mono1', 'Date': '18/03/2021', 'Time': '18:25', 'Camera': 'monochromatic'}

To read the file you have, you could use:要读取您拥有的文件,您可以使用:

with open('test.txt') as f:
    lines = iter(f)  # An iterator over the lines of the file
    info = {}
    for line in lines:  # gets a line (key)
        # rstrip() removes the newline at the end of each line
        info[line.rstrip()] = next(lines).rstrip() # next() fetches another line (value)
print(info)

(same output) (相同的输出)

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

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