2

I am trying to create a new directory folder using azure functions for python. But I am not able to create a new directory and file in azure functions for python. I got below error.

Whenever I am executing Azure functions for python on local then it's working fine but not on azure.

Error: -

Error in folder creation: [Errno 30] Read-only file system: './HttpTrigger/logs'

I am trying to create new log folder in HttpTrigger function, but got above error.

Please check the below code: -

import logging
import struct
import sys
import azure.functions as func
import os

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    try:
        if not os.path.exists('./HttpTrigger/logs'):
            logging.info('Inside Forlder Creation')
            os.makedirs('./HttpTrigger/logs')

        f= open("test.txt","w+")
        for i in range(10):
            logging.info('Inside For')
            f.write("This is line %d\r\n" % (i+1))
        logging.info('Outside For')
        f.close() 
        return func.HttpResponse("Created",
            status_code=200
        )
    except Exception as e:
        return func.HttpResponse(f"Error in floder creation : {e}", status_code=400)

Is there any way to create a new directory in azure functions for python? Please let me know if there is any way.

Akshay Godase
  • 239
  • 7
  • 15

4 Answers4

4

If you need to do some file processing temporary then azure function provides a temporary directory. temporary directory in azure functions

Here is a code snippet.

import tempfile
from os import listdir
    
tempFilePath = tempfile.gettempdir()
fp = tempfile.NamedTemporaryFile()
fp.write(b'Hello world!')
filesDirListInTemp = listdir(tempFilePath)

For reference.

geertjanvdk
  • 3,440
  • 24
  • 26
Muhammad Shafiq
  • 129
  • 1
  • 9
2

The point of Azure functions (and more generally serverless functions) is to be triggered by a specific event, execute some logic and then exit. It's not like a regular server where you have access to the file system and where you can read/write files. Actually, you can't be sure it will always be executed by the same physical machine ; Azure abstracts all this concepts for you (hence the name "serverless").

Now, if you really need to write files, you should have a look at Blob storage. It's a cloud-native service where you can actually download and upload files. From your Azure function, you'll have to use the Blob storage API to manipulate the files.

frankie567
  • 1,703
  • 12
  • 20
0

Your actual app folder will be reading from a zip, so won't allow you to create folders or files. However you should be able to create temporary directories in like the /tmp directory. That said, you shouldn't rely on them being there and are (as the name implies) intended to be temporary. So would stick with @frankie567 advice on using something like Azure Storage to store artifacts you expect to pull later.

jeffhollan
  • 3,139
  • 15
  • 18
0

You could create file or directory in the temp folder or the function execution folder, cause the content in temp folder won't be saved all the time so you could create directory in the execution directory, you could get the directory with Context bingding the use function_directory to get it. Further more information you could refer to this doc: Python developer guide.

And the below is my test code, I create the folder and file then send the filename as the response

import logging
import os
import time
import datetime
import json
import azure.functions as func


def main(req: func.HttpRequest,context: func.Context) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    t = datetime.datetime.now().strftime("%H-%M-%S-%f")
    foldername=context.function_directory+"/newfolder"+t
    os.makedirs(foldername)
    suffix = ".txt"
    newfile= t+suffix
    os.getcwd()
    os.chdir(foldername)
    if not os.path.exists(newfile):
        f = open(newfile,'w')
        f.write("test")
        f.close()
    data=[]
    for filename in os.listdir(context.function_directory):
        print(filename)
        d1={"filename":filename}
        data.append(d1)
    jsondata=json.dumps(data)


    return func.HttpResponse(jsondata)

Here is the result picture, you could see I could create the folder and file.

enter image description here

George Chen
  • 13,703
  • 2
  • 11
  • 26
  • @Akshay Godase, if this could help you, please accept it as the answer. Thanks! – George Chen Sep 18 '19 at 15:09
  • I tried using context to get the function directory and write file to that directory.Looks like there is still the permission issue. Error :Result: Failure Exception: OSError: [Errno 30] Read-only file system: '/home/site/wwwroot/confluence/audio_20200629.wav' . Could you please help. – Abhijeet Jun 29 '20 at 11:01