将Python数据帧作为CSV写入Azure Blob

2024-04-20 13:13:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个关于从/到Azure blob读写Python对象的问题。

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

我尝试使用函数从文本创建blob&u;从流创建blob&u 但都不管用。

将dataframe转换为字符串并使用从文本创建blob\u函数 将文件写入blob,但作为纯字符串,而不是csv。

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

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


Tags: 文件csvto数据对象函数字符串文本
1条回答
网友
1楼 · 发布于 2024-04-20 13:13:29

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', 'OutFilePy.csv', 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

希望对你有帮助。

相关问题 更多 >