【问题标题】:Create csv file in Cloud Storage using Cloud Functions使用 Cloud Functions 在 Cloud Storage 中创建 csv 文件
【发布时间】:2019-09-27 02:56:57
【问题描述】:

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

如何使这个文件可写?

【问题讨论】:

  • 您没有关闭 test.csv 的句柄。该文件保持锁定状态,因此您无法再次创建和写入。在您的设计中,不要使用 /tmp 目录。使用内存缓冲。
  • @TeeKay 你找到解决办法了吗?
  • 你为什么用 google-cloud-platform 标记它?这是一个关于简单文件操作的问题!

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


【解决方案1】:

正如@saccodd 所说,问题是您只有/tmp directory 的写入权限。所以替换:

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

与:

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

会解决错误,但建议在再次处理之前关闭文件。引用Python official documentation

处理文件时最好使用with 关键字 对象。优点是文件在其后正确关闭 套件完成,即使在某个时候引发了异常。使用 with 也比编写等效的 try-finally 块要短得多

所以最好替换

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

与:

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

【讨论】:

  • 我认为使用“with”是所提问题的一个小问题。更何况,它只是 Cloud Function 中的一个临时文件。
【解决方案2】:

尝试替换:

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

与:

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

因为您仅在 /tmp 中具有写入权限

【讨论】: