【问题标题】:Files uploaded to s3 are missing content上传到 s3 的文件缺少内容
【发布时间】:2021-01-16 13:09:16
【问题描述】:

我正在尝试将一系列文件从 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。
  • 使用 with 语句没有修复错误。我应该编辑问题以使用该语法吗?
  • 写入后上传前需要关闭。您在上传后添加了关闭。
  • 这是非常真实和非常正确的。这解决了这个问题。非常感谢

标签: python pandas amazon-s3 boto3


【解决方案1】:

您需要先关闭文件,以便将数据写入文件系统。

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() 来完成,但这里不需要。

【讨论】:

  • 是 cmets 中的其他人提供了所有信息,但我还是想把它们放在一起。很高兴听到它有用。
  • 哎呀顺便说一句,那里有一个额外的'text =',虽然它并没有真正伤害任何东西,但现在没有杂物就更清楚了
猜你喜欢
  • 2018-07-24
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-13
相关资源
最近更新 更多