在GCS存储桶中存储的CSV文件的每一行中添加回车符 [英] Adding Carriage return to every line in a CSV file stored in a GCS bucket

查看:89
本文介绍了在GCS存储桶中存储的CSV文件的每一行中添加回车符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在CSV文件中的每行末尾添加回车符,该文件可在一个GCS存储桶.我想将修改后的数据存储在同一GCS存储桶中的新文件中.我们观察到的是尽管我们正在将数据写入新的CSV文件,但它会覆盖原始文件.

I have a requirement to add carriage return at the end of each line in a CSV file that is available in a GCS bucket. I want to store the modified data in a new file in same GCS bucket. What we observed is though we are writing the data to new CSV file, it is overriding the original file.

下面是我用于该任务的代码段.

Below is the code snippet that i am using for the task.

有人可以在不更改原始文件中数据的情况下帮助我吗?

Can someone help me on how this can be achieved without changing the data in original file.

谢谢,Hemaraju

Thanks, Hemaraju

from google.cloud import storage
storage_client = storage.Client.from_service_account_json(r"C:\Users\XXXXX\Downloads\GCP-Key\XXXX.json")

bucket = storage_client.get_bucket('test-export-bucket-XXXX')
blob = bucket.blob('new/test_file.csv')
destination_blob = bucket.blob('test/modified_test_file.csv')
data = blob.download_as_string()

count = 0
for line in data.splitlines():
    count +=1
    print(line)
    newline = line.decode('utf8') + '\r\n'
    print(newline)
    destination_blob.upload_from_string(newline)

推荐答案

这里只是说明@Guillaume解释的内容(如果不清楚).请选择他的答案作为正确答案.

Just here to illustrate what @Guillaume explained in case it wasn't clear. Please select his answer as the correct one.

text_buffer = ""
for line in data.splitlines():
   text_buffer += line.decode('utf8') + '\r\n'
   
destination_blob.upload_from_string(text_buffer)

这篇关于在GCS存储桶中存储的CSV文件的每一行中添加回车符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆