首页 > 解决方案 > 使用“upload_file”在 AWS S3 中上传 csv 在 S3 中获取 0 字节

问题描述

我想在我的 AWS S3 存储桶中上传我的本地 CSV 文件

我试过:

s3 = boto3.resource('s3')

s3.meta.client.upload_file('verified_path_of_my_CSV', 'bucket_name', 'My_csv')

但我的存储桶中有一个 0 字节的 CSV

我也尝试:

s3_client = boto3.resource('s3')

bucket = s3.Bucket('bucket_name')
s3.Object(bucket, 'My_csv').put(Body=open(csv_path, 'rb'))

但我收到此错误:

Traceback (most recent call last):
  File "test-text.py", line 109, in <module>
    main()
  File "test-text.py", line 88, in main
    upload_csv(bucket, 'name_of_my_csv', 'My_path')
  File "test-text.py", line 56, in upload_csv
    s3.Object(bucket, 'My_csv').put(Body=open(csv_path, 'rb'))
 ...
  File "/home/toto/.local/lib/python3.7/site-packages/botocore/handlers.py", line 219, in validate_bucket_name
    if VALID_BUCKET.search(bucket) is None:
TypeError: expected string or bytes-like object

如何在 S3 中上传我的 CSV?

提前致谢


解决者:

实际上,当我制作 CSV 时,我会这样写:

with open('job_file.csv', 'w') as csvfile:
    filewriter = csv.writer(csvfile, delimiter=',')
    text = process_text_analysis(bucket, file, True)
    filewriter.writerow(["doc1", text])
    upload_csv(bucket, key_s3, 'my_local_csv_path')

但是我upload_csv()在完成我的 CSV 之前执行,正确的方法是将我的上传功能移出块:

with open('job_file.csv', 'w') as csvfile:
    filewriter = csv.writer(csvfile, delimiter=',')
    text = process_text_analysis(bucket, file, True)
    filewriter.writerow(["doc1", text])

upload_csv(bucket, key_s3, 'my_local_csv_path')

我知道愚蠢的错误:),但是这个附加......

希望此编辑将来可以避免此类问题;)

感谢大家,尝试解决我的问题

标签: pythonamazon-web-servicesamazon-s3

解决方案


这是使用 s3 作为客户端

 aws_session = boto3.Session()
 s3_client = aws_session.client('s3')
 local_path = os.path.join(root, file)
 bucket_name= "abc"
 s3_client.upload_file(localpath, bucket_name, s3_file)

in your case 

s3_client.upload_file('verified_path_of_my_CSV',bucket_name,"my_csv.csv")

使用 s3 作为资源

aws_session = aws_session.resource("s3")
s3_resource = self.aws_session.resource("s3")

def s3_upload(self, s3_bucket, s3_key, local_file_path):
        """
        To upload file to a S3 bucket
        :param s3_bucket: Bucket name
        :param s3_key: Key of the file in the S3 bucket
        :param local_file_path: Location of the file to upload
        :return:
        """
        fp = open(local_file_path, "rb")
        file_data = fp.read()
        mime_type, temp = self.mime.guess_type(local_file_path)
        s3_params = {
            "Key": s3_key
            , "Body": file_data
        }
        if mime_type is None:
            mime_type = "application/octet-stream"
        s3_params["ContentType"] = mime_type
        s3_resource.Bucket(s3_bucket).put_object(**s3_params)

推荐阅读