使用 python 将 CSV 文件上传到 Microsoft Azure 存储帐户

Upload CSV file into Microsoft Azure storage account using python

我正在尝试使用 python 将 .csv 文件上传到 Microsoft Azure 存储帐户。我找到了 C-sharp 代码来将数据写入 blob 存储。但是,我不懂 C# 语言。我需要使用 python.

上传 .csv 文件

有没有python将CSV文件内容上传到Azure存储的例子?

我使用 this 参考文献 link 找到了解决方案。我的以下代码非常适合 上传 下载 .csv 文件。

#!/usr/bin/env python

from azure.storage.blob import BlockBlobService
from azure.storage.blob import ContentSettings

block_blob_service = BlockBlobService(account_name='<myaccount>', account_key='mykey')
block_blob_service.create_container('mycontainer')

#Upload the CSV file to Azure cloud
block_blob_service.create_blob_from_path(
    'mycontainer',
    'myblockblob.csv',
    'test.csv',
    content_settings=ContentSettings(content_type='application/CSV')
            )

# Check the list of blob
generator = block_blob_service.list_blobs('mycontainer')
for blob in generator:
    print(blob.name)

# Download the CSV file From Azure storage
block_blob_service.get_blob_to_path('mycontainer', 'myblockblob.csv', 'out-test.csv')

根据我的理解,我认为您想将 csv 文件的数据上传到 Azure Table 存储中。根据doc of pythoncsv package & the offical tutorial for Azure Storage Python SDK,我制作了如下示例代码和csv数据。

例如我的测试csv文件的数据如下。

Name,Species,Score
Kermit,Frog,10
Ms. Piggy,Pig,50
Fozzy,Bear,23

和示例代码。

import csv
from azure.storage.table import TableService, Entity

table_service = TableService(account_name='myaccount', account_key='mykey')
table_service.create_table('csvtable')

csvfile = open('test.csv', 'r')
fieldnames = ('Name','Species','Score')
reader = csv.DictReader(csvfile)
rows = [row for row in reader]
for row in rows:
  index = rows.index(row)
  row['PartitionKey'] = '1'
  row['RowKey'] = '%08d' % index
  table_service.insert_entity('csvtable', row)

希望对您有所帮助。