gpt4 book ai didi

python-3.x - 使用 Cloud Functions 在 Cloud Storage 中创建 csv 文件

转载 作者:行者123 更新时间:2023-12-04 02:48:43 25 4
gpt4 key购买 nike

我一直在尝试从 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'

如何使这个文件可写?

最佳答案

@saccodd说问题是你在 /tmp directory中只有写权限.所以更换:

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

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

将解决错误,但建议在再次处理之前关闭文件。引用 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



所以最好更换
csv = open('test.csv', "w") #ERROR HERE 
csv.write(message)

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

关于python-3.x - 使用 Cloud Functions 在 Cloud Storage 中创建 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56056590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com