繁体   English   中英

为什么在Python中读取csv文件时会得到字符串而不是字典?

[英]Why am I getting a string instead of a dictionary while reading a csv file in Python?

我正在使用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])

读取此文件时,我得到一个length = 1的列表。我得到了通过写row = info[0]保存的整个字典。 但是当我得到type(row) ,它是str而不是字典。 为什么会这样,又如何获得字典?

使用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"]

暂无
暂无

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

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