[英]Files uploaded to s3 are missing content
我正在嘗試從 Pandas 數據框中將一系列文件上傳到 s3。 我用來做的代碼如下所示
import os
import boto3
import pandas as pd
from botocore.exceptions import NoCredentialsError
ACCESS_KEY = os.environ['KEY_ID']
SECRET_KEY = os.environ['SECRET_KEY']
def upload_to_aws(local_file, bucket, s3_file):
s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY)
try:
s3.upload_file(local_file, bucket, s3_file)
print("Upload Successful")
return True
except NoCredentialsError:
print("Credentials not available")
return False
except FileNotFoundError:
print("The file was not found")
return False
df = pd.read_csv('file.csv')
description = df.description.iloc[50]
text_file = open(f"textfile.txt", "w")
text = text_file.write(description)
upload_to_aws("textfile.txt",'bucket-name',"test.txt")
text_file.close()
我正在抓取存儲為字符串的數據框元素並將其寫入文本文件。 該文件是在本地創建的,沒有問題,但是 s3 上的版本顯示沒有內容。
我的代碼導致了這個問題,我如何確保內容顯示出來? 如果有更聰明的方法來解決這個問題,我很想知道。
您需要先關閉文件,以便將數據寫入文件系統。
with open(f"textfile.txt", "w") as text_file:
text_file.write(description)
#now the with block ends and calls close() on the file and it's written to disk
upload_to_aws("textfile.txt",'bucket-name',"test.txt")
如果您想讓文件保持打開狀態以寫入更多內容,但您在這里不需要它,也可以使用 flush() 來完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.