[英]How to stream a large gzipped .tsv file from s3, process it, and write back to a new file on s3?
我有一個大文件s3://my-bucket/in.tsv.gz
我想加載和處理,將其處理后的版本寫回 s3 output 文件s3://my-bucket/out.tsv.gz
.
in.tsv.gz
而不將所有文件加載到 memory (它不適合內存) 在下面的代碼中,我展示了我是如何考慮從 s3 加載輸入 gzip 壓縮的 dataframe,以及如果.tsv
位於本地bucket_dir_local =./
,我將如何編寫它。
import pandas as pd
import s3fs
import os
import gzip
import csv
import io
bucket_dir = 's3://my-bucket/annotations/'
df = pd.read_csv(os.path.join(bucket_dir, 'in.tsv.gz'), sep='\t', compression="gzip")
bucket_dir_local='./'
# not sure how to do it with an s3 path
with gzip.open(os.path.join(bucket_dir_local, 'out.tsv.gz'), "w") as f:
with io.TextIOWrapper(f, encoding='utf-8') as wrapper:
w = csv.DictWriter(wrapper, fieldnames=['test', 'testing'], extrasaction="ignore")
w.writeheader()
for index, row in df.iterrows():
my_dict = {"test": index, "testing": row[6]}
w.writerow(my_dict)
編輯: smart_open看起來像 go 的方式。
要下載文件,您可以直接在 python 中 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ S3 object 。 我建議閱讀整篇文章,但其中的一些關鍵內容
import boto3
s3 = boto3.client('s3', aws_access_key_id='mykey', aws_secret_access_key='mysecret') # your authentication may vary
obj = s3.get_object(Bucket='my-bucket', Key='my/precious/object')
import gzip
body = obj['Body']
with gzip.open(body, 'rt') as gf:
for ln in gf:
process(ln)
不幸的是,S3 不支持真正的流輸入,但是這個 SO 答案有一個實現,可以將文件分塊並將每個塊發送到 S3。 雖然不是“真正的流”,但它可以讓您上傳大文件,而無需將整個內容保存在 memory
這是一個從 s3 讀取文件並使用smart_open
將其寫回 s3 的虛擬示例
from smart_open import open
import os
bucket_dir = "s3://my-bucket/annotations/"
with open(os.path.join(bucket_dir, "in.tsv.gz"), "rb") as fin:
with open(
os.path.join(bucket_dir, "out.tsv.gz"), "wb"
) as fout:
for line in fin:
l = [i.strip() for i in line.decode().split("\t")]
string = "\t".join(l) + "\n"
fout.write(string.encode())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.