我一直试图从Cloud Functions中的字符串创建一个csv文件。它将文件临时存储在/ tmp文件夹中。然后文件进入存储桶。
以下是我的代码-
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')
我收到以下错误-
File "/user_code/main.py", line 30, in hello_main csv = open('test.csv',
"w") OSError: [Errno 30] Read-only file system: 'test.csv'
如何使该文件可写?
答案 0 :(得分:1)
尝试更换:
csv = open('test.csv', "w")
具有:
csv = open('/tmp/test.csv', "w")
因为您仅在/ tmp中具有写权限
答案 1 :(得分:0)
正如@saccodd所说,问题是您仅在/tmp
directory中具有写权限。因此,替换:
csv = open('test.csv', "w")
具有:
csv = open('/tmp/test.csv', "w")
将解决该错误,但建议先关闭文件再处理。引用Python official documentation:
在处理文件时,最好使用with关键字 对象。好处是文件在其被正确关闭后 套件完成,即使在某个时候引发异常。使用 还比编写等效的try-finally块
短得多
所以最好替换
csv = open('test.csv', "w") #ERROR HERE
csv.write(message)
具有:
with open('/tmp/test.csv', "w") as csv:
csv.write(message)