如何从dropbox读取csv文件作为字典(从csv.DictReader()读取)?

时间:2018-03-16 13:38:44

标签: python-3.x csv dictionary dropbox-api

我尝试使用

从Dropbox读取csv文件
  

md,res = dbx.files_download(path)

按照此link的建议
这是我试图阅读的csv:csv_file_image
res.content开始,我从csv文件中获取了丑陋的数据 是否有任何方法可以更好地读取数据,如使用:

import csv
with open(file) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['name'])

我想将csv文件作为字典读取,但我得到的数据是:response_data_image

1 个答案:

答案 0 :(得分:1)

我通过将res.content转换为可迭代的obj:

找到了这个解决方案
import csv
import dropbox

path = '' # file path which is needed to be read
dbx = dropbox.Dropbox('YOUR_ACCESS_TOKEN')
md, res = dbx.files_download(path)
data = res.content # data in ugly shape
# Now data is needed to be decoded from bytes to unicode and then str.split()
data = data.decode('utf-8')
data = data.split('\n')
# Now data is an iterable object, so csv.DictReader can be used
reader = csv.DictReader(data)
# Loop to get data using key value from reader dict
for row in reader:
    row['nameen']    # 'nameen' is the key value in my case