我正在嘗試將字典附加到 csv 檔案,然后回傳到字典。我不想寫它只是為了附加它。
from tkinter import *
import csv
dictionary = {"Alex" : 5, "Ben": 10}
with open("dict.csv", "a") as csv_file:
writer = csv.writer(csv_file)
for key, value in dictionary.items():
writer.writerow([key, value])
with open("dict.csv") as csv_file:
reader = csv.reader(csv_file)
dictionary = dict(reader)
print(dictionary)
我想要輸出 {"Alex" : 5, "Ben": 10} 它會得到我 ValueError: dictionary update sequence element #1 has length 0; 2 是必需的。有人可以幫忙嗎?
uj5u.com熱心網友回復:
為什么ValueError?
因為當您嘗試使用 dict 將 reader 轉換為dict(reader)
dict 實際上需要一個元組序列(實際上是任何長度為 2 的迭代器)但 reader 是一個序列序列,所以 dict 抱怨 reader 序列的第一個元素是上面有零個元素的序列...
我能做什么
撰寫部分解決方案是可以的(但它可以改進csv.DictWriter)真正的問題是當你想閱讀它時......
from tkinter import *
import csv
dictionary = {"Alex" : 5, "Ben": 10}
with open("dict.csv", "a") as csv_file:
writer = csv.writer(csv_file)
for key, value in dictionary.items():
writer.writerow([key, value])
with open("dict.csv") as csv_file:
reader = csv.reader(csv_file)
dictionary = {}
for row in reader:
if row:
dictionary.update({row[0]: row[1]})
print(dictionary)
uj5u.com熱心網友回復:
在“寫入階段”中,您將 dict拆分為鍵值對,并每行撰寫一個鍵值對:
dictionary = {"Alex": 5, "Ben": 10}
with open("dict.csv", "a") as csv_file:
writer = csv.writer(csv_file)
for key, value in dictionary.items():
writer.writerow([key, value])
{"Alex" : 5, "Ben": 10}被寫入dict.csv,如:
Alex,5
Ben,10
所以,在你的“閱讀階段”,你需要做相反的事情并將鍵值對的行連接到一個字典中:
new_dictionary = {}
with open("dict.csv") as csv_file:
reader = csv.reader(csv_file)
for row in reader:
key = row[0]
value = row[1]
new_dictionary[key] = value
print(dictionary)
print(new_dictionary)
{'Alex': 5, 'Ben': 10}
{'Alex': '5', 'Ben': '10'}
但是,整數被讀取為字串,因此您需要自己轉換它們:
...
value = int(row[1])
...
現在新的字典等于舊的字典:
{'Alex': 5, 'Ben': 10}
{'Alex': 5, 'Ben': 10}
通常,對于使用csv模塊讀取/寫入 CSV,最好使用以下命令打開檔案newline='':
with open('dict.csv', 'a', newline='') as ...
這告訴開啟者不要解釋和“修復”不一致的換行符——這可能對常規文本有好處,但在讀取 CSV 檔案時可能不需要。CSV 模塊的讀取器和寫入器具有特定于 CSV 檔案的換行符的特殊知識/處理。
uj5u.com熱心網友回復:
您遇到的問題是,當您回圈瀏覽字典專案時,您在加載它們時將它們添加為串列,您試圖將串列轉換為串列無法執行的字典,因為它們沒有鍵值對。
這是修復它的一種方法:
import csv
data_dictonary = {"Alex" : 5, "Ben": 10}
# append to file
with open("dict.csv", "a") as csv_file:
writer = csv.writer(csv_file)
for key, value in data_dictionary.items():
writer.writerow([key, value])
# read file and check contents
with open("dict.csv") as csv_file:
dictionary = csv.DictReader(csv_file)
print(dictionary)
來源
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/423434.html
標籤:
