加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

将Python DataFrame作为CSV写入Azure Blob

发布时间:2020-12-20 11:04:08 所属栏目:Python 来源:网络整理
导读:我有两个关于从/向Azure blob读取和编写 Python对象的问题. 1)有人能告诉我如何将Python数据帧作为csv文件直接写入Azure Blob而不在本地存储吗? 我尝试使用函数create_blob_from_text create_blob_from_stream ?但它们都不起作用. 将数据帧转换为字符串并使
我有两个关于从/向Azure blob读取和编写 Python对象的问题.

1)有人能告诉我如何将Python数据帧作为csv文件直接写入Azure Blob而不在本地存储吗?

我尝试使用函数create_blob_from_text& create_blob_from_stream
?但它们都不起作用.

将数据帧转换为字符串并使用create_blob_from_text函数
?将文件写入blob但是作为普通字符串而不是csv.

df_b = df.to_string()
    block_blob_service.create_blob_from_text('test','OutFilePy.csv',df_b)

2)如何直接将Azure blob存储中的json文件直接读入Python?

解决方法

1) Can someone tell me how to write Python dataframe as csv file
directly into Azure Blob without storing it locally?

你可以使用pandas.DataFrame.to_csv方法.

示例代码:

from azure.storage.blob import (
    BlockBlobService
)
import pandas as pd
import io

output = io.StringIO()
head = ["col1","col2","col3"]
l = [[1,2,3],[4,5,6],[8,7,9]]
df = pd.DataFrame (l,columns = head)
print df
output = df.to_csv (index_label="idx",encoding = "utf-8")
print(output)

accountName = "***"
accountKey = "***"
containerName = "test1"
blobName = "test3.json"

blobService = BlockBlobService(account_name=accountName,account_key=accountKey)

blobService.create_blob_from_text('test1',output)

输出结果:

enter image description here

2.How to directly read a json file in Azure blob storage directly into Python?

示例代码:

from azure.storage.blob import (
    BlockBlobService
)

accountName = "***"
accountKey = "***"
containerName = "test1"
blobName = "test3.json"

blobService = BlockBlobService(account_name=accountName,account_key=accountKey)

result = blobService.get_blob_to_text(containerName,blobName)

print(result.content)

输出结果:

enter image description here

希望它能帮到你.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读