pythonazurecsvazure-functionsread-write

How to Read and Write inside csv files using python with Azure Functions


In the Azure functions, and using python, how can i read csv files(and write)?

here is my code:

import datetime
import logging

import azure.functions as func
import csv
import traceback

def aprint(info):
    logging.info("Azure Print: "+str(info))
def read_csv_file(file_path):
        with open(file_path, 'r') as csvfile:
            aprint('Inside the file')
            reader = csv.reader(csvfile)
            for row in reader:
                # Process each row of data
                aprint(row)

def main(mytimer: func.TimerRequest) -> None:
    utc_timestamp = datetime.datetime.utcnow().replace(
              tzinfo=datetime.timezone.utc).isoformat()
    logging.info("Program Has Started")  
    read_csv_file('general_DB.csv')
    if mytimer.past_due:
        logging.info('The timer is past due!')
        
        logging.info("Process passed successfully(thanks to timer)")

    logging.info('Python timer trigger function ran at %s', utc_timestamp)

and here are the logs when i run the code in azure:


2023-05-26T21:59:14Z   [Information]   Executing 'Functions.TimerTrigger1' (Reason='This function was programmatically called via the host APIs.', Id=)
2023-05-26T21:59:14Z   [Verbose]   Sending invocation id:
2023-05-26T21:59:14Z   [Verbose]   Posting invocation id:
2023-05-26T21:59:14Z   [Information]   Program Has Started
2023-05-26T21:59:14Z   [Information]   Azure Print: Starting Read
2023-05-26T21:59:14Z   [Information]   Azure Print: Entered the function
2023-05-26T21:59:14Z   [Error]   Executed 'Functions.TimerTrigger1' (Failed, Id=, Duration=90ms)

I have my csv file in the same place as my .py file in the cloud, From the troubleshooting that i have done i figured out that the issue comes with opening the file but i cannot find anything online on how i could fix it


Solution

  • I have referred these links for the Timer trigger for Azure Functions,Python developer and CSV File Reading and Writing

    import  datetime
    import  logging
    import  os
    import  azure.functions  as  func
    import  csv
    def  read_csv_file(file_path):
    data = []
    try:
    with  open(file_path,  'r')  as  csv_file:
    csv_reader = csv.reader(csv_file)
    for  row  in  csv_reader:
    data.append(row)
    except  Exception  as  e:
    logging.error(f"Error reading CSV file: {e}")
    return  data
    def  write_csv_file(file_path,  data):
    try:
    with  open(file_path,  'a',  newline='')  as  csv_file:
    csv_writer = csv.writer(csv_file)
    for  row  in  data:
    csv_writer.writerow(row)
    except  Exception  as  e:
    logging.error(f"Error writing to CSV file: {e}")
    def  main(mytimer:  func.TimerRequest)  ->  None:
    utc_timestamp = datetime.datetime.utcnow().replace(
    tzinfo=datetime.timezone.utc).isoformat()
    if  mytimer.past_due:
    logging.info('The timer is past due!')
    logging.info('Python timer trigger function ran at %s',  utc_timestamp)
    function_directory = os.getcwd()
    file_name = 'Hello.csv'
    file_path = os.path.join(function_directory,  file_name)
    csv_data = read_csv_file(file_path)
    for  row  in  csv_data:
    logging.info(row)
    csv_data = [
    ['Index',  'Organization Id',  'Name',  'Website',  'Country',  'Description',  'Founded',  'Industry',  'Number of employees'],
    
    ['107',  'AB0d41d5b5d22c',  'Ferrell LLC',  'https://price.net/',  'Papua New Guinea',  'Horizontal empowering knowledgebase',  '1990',  'Plastics',  '3498']
    
    ]
    write_csv_file(file_path,  csv_data)
    for  row  in  csv_data:
    logging.info(row)
    logging.info("CSV file processed successfully.")
    
    with  open(file_path,  'a',  newline='')  as  csv_file:
    
    with  open(file_path,  'w',  newline='')  as  csv_file:
    
    file_path = "c:/hello.csv"  
    csv_data = read_csv_file(file_path)
    

    Output:

    enter image description here

    enter image description here

    enter image description here