I have been trying to create a csv file from a string in Cloud Functions. It is storing the file temporarily in /tmp folder. Then the file goes to the bucket.

Following is my code -

def upload_blob(bucket_name, source_file_name, destination_blob_name):

    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)
    blob.upload_from_file(source_file_name)

message = "Data for CSV file"
csv = open('test.csv', "w")    #ERROR HERE
csv.write(message)
with open('/tmp/test.csv', 'r') as file_obj:
    upload_blob('test-bucket', file_obj, 'test.csv')

I am getting the following error -

File "/user_code/main.py", line 30, in hello_main csv = open('test.csv', 
"w") OSError: [Errno 30] Read-only file system: 'test.csv'

How to make this file writable?

2 Answers

1
saccodd On

Try replacing:

csv = open('test.csv', "w") 

with:

csv = open('/tmp/test.csv', "w") 

since you have write permissions only in /tmp

0
llompalles On

As @saccodd said the issue is that you only have write permissions in the /tmp directory. So replacing:

csv = open('test.csv', "w") 

with:

csv = open('/tmp/test.csv', "w") 

would solve the error but it is recommended to close the file before handling it again. Quoting the Python official documentation:

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks

So better replace

csv = open('test.csv', "w") #ERROR HERE 
csv.write(message) 

with:

with open('/tmp/test.csv', "w") as csv: 
    csv.write(message)