I am writing a dictionary in a CSV file using this:
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])
While reading this file, I get a list of length = 1. I get the whole dictionary that I saved by writing row = info[0]
. But when I get the type(row)
, it is str
and not the dictionary. Why is that and how can I get the dictionary?
Using csv.DictReader and csv.DictWriter, look at the sample code
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"]
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.