Upload CSV file into Microsoft Azure storage account using python

青春壹個敷衍的年華 提交于 2019-12-21 18:03:51

问题


I am trying to upload a .csv file into Microsoft Azure storage account using python. I have found C-sharp code to write a data to blob storage. But, I don't know C# language. I need to upload .csv file using python.

Is there any example of python to upload contents of CSV file to Azure storage?


回答1:


I found the solution using this reference link. My following code perfectly work for uploading and downloading .csv file.

#!/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')



回答2:


Based on my understanding, I think you want to upload the data of csv file into Azure Table Storage. According to the doc of pythoncsv package & the offical tutorial for Azure Storage Python SDK, I made the sample code & csv data as below.

For example, the data of my testing csv file as below.

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

And the sample code.

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)

Hope it helps.



来源:https://stackoverflow.com/questions/41978833/upload-csv-file-into-microsoft-azure-storage-account-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!