簡體   English   中英

將 csv 文件讀取到字典 - 僅讀取第一個鍵+值

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

我有一個 function 將 csv 文件讀入字典,但下一個迭代器似乎不起作用,因為它只讀取第一對鍵+值。

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

我的 csv 文件的結構是這樣的:

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

字典返回是:

{'Test Name': 'mono1'}

知道發生了什么嗎? 還是一種無需更改其結構即可讀取文件的更好方法?

您的文件不是 CSV。 它的結構需要如下:

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

這將與以下內容一起閱讀:

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'}

要讀取您擁有的文件,您可以使用:

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)

(相同的輸出)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM