我正在使用以下文件在CSV文件中编写字典:
self.idSelf += 1
self.tweet["tweet"] = tweetText
self.tweet["id"] = id
self.tweet["sequence"] = self.idSelf
self.tweet["created_at"] = created_at
with open('#KXIPvMI-2018-05-04.csv', 'a') as csv_file:
writer = csv.writer(csv_file)
a = [self.tweet]
print a[0]['tweet']
writer.writerow([self.tweet])
在阅读此文件时,我得到一个长度= 1的列表。我通过编写row = info[0]
得到了我保存的整个字典。但是当我得到type(row)
时,它是str
而不是字典。为什么这样,我怎么能得到字典?
答案 0 :(得分:1)
使用csv.DictReader和csv.DictWriter,查看示例代码
import csv
di = {}
di["id"] = 1
di["val"] = "val"
with open("test.csv","a") as csv_file:
writer = csv.DictWriter(csv_file,di.keys())
writer.writerow(di)
with open("test.csv") as csv_file:
reader = csv.DictReader(csv_file,di.keys())
for row in reader:
print row["id"]