pythonfile-writing

How do I redirect file writing location for a python package?


I have a package that uses one temporary file, and this file is written and loaded using the package functions. The problem is that I am using this package with Azure Functions, and you are only allowed to write to a special location there. How can I force this package to write to this location? The path is defined inside the package as a global variable:

### foo_package.py ###

path = 'file.json'

def read_file():
    with open(path, "r") as file:
        json_data = json.load(file)

def save_file(json_data):
    with open(path, "w") as file:
        json.dump(json_data, file)


def foo_function():
    file = load_file()
    ...
    save_file(json_data)

### my_code.py ###

from foo_package import foo_function

foo_function() # writes to ./, but i need to write to /some/path

Solution

  • Since path is specified as a relative path of 'file.json', you can change your working directory with os.chdir before calling foo_function, and change the working directory back if needed:

    ### my_code.py ###
    import os
    from foo_package import foo_function
    
    cwd = os.getcwd()
    os.chdir('/some/path')
    foo_function()
    os.chdir(cwd)