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

标签 python-3.x csv google-cloud-platform google-cloud-functions google-cloud-storage

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

相关文章:

Python .csv 编写器

docker - 如何在 Kubernetes pod 之间共享存储?

python - 从 GCP 安装文档运行 "[CRITICAL] WORKER TIMEOUT"时,日志中的 "Hello Cloud Run with Python"

google-cloud-platform - 允许未经身份验证的参数不起作用

python - 如何从文本文件中删除直到特定字符串的所有行?

mysql - Amazon Data Pipeline "Load S3 Data to RDS MySQL"查询格式?

python - 在新的virtualenv中安装wheel软件包时,导入旧django项目模型的任何方法

c++ - 来自带有分隔符的 std::getline 的段错误

python - 如何删除另一个特定字符前面的特定字符?

python - 如何在 python 中将 xml 文件转换为 csv 输出?