简体   繁体   中英

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.

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

My csv file is structured this way:

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. 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:

{'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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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