简体   繁体   中英

Upload CSV file into Microsoft Azure storage account using python

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?

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')

Based on my understanding, I think you want to upload the data of csv file into Azure Table Storage. According to the doc of python csv 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM