Skip to main content

How to: Read a local file

This tutorial shows you how to read a file that you have uploaded in the .zip alongside your code.

warning

ArupCompute utilises Microsoft Azure Functions to run your code. This is a 'serverless' system - meaning that the code is run on any available machine that Microsoft provides.

Your code is loaded onto a machine when it is needed. All data is wiped when the code is no longer actively running. Additionally all code is run in a security sandbox.

The takeaway is that the below method should only be used for reading data e.g. configuration or supporting data.

It should not be used for persisting any information, this must all be done in an alternative way e.g. returning data to the user, writing to databases, posting data to other systems etc.

In the below example we upload a file called myfile.txt alongside our python code. The structure of the uploaded .zip looks like this:

read_local_zip

import pathlib

def read_local_file(repeat: int) -> str:
"""Read local file

Demonstrates how to a read a local file that is uploaded alongside the python code

Args:
repeat: Number of times to repeat the text contained within the local file

.. codeauthor:: Hugh Groves <[email protected]>
"""

# Azure function that ArupCompute runs your python code in
# invokes your code in a non-standard way
# below syntax using pathlib.Path needed to navigate to
# the correct folder on the target filesystem
# This will also work when running code locally for testing
with open(pathlib.Path(__file__).parent / 'myfile.txt') as f:
lines = f.read()

output = ''
for x in range(repeat):
output = output + lines + '\n'

return output