python - 使用“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')
我知道愚蠢的错误:),但是这个附加......
希望此编辑将来可以避免此类问题;)
感谢大家,尝试解决我的问题
解决方案
这是使用 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)
推荐阅读
- html - 是否允许在 td 中包含表单元素?
- php - 会话中的 PHP 购物车显示不同的产品
- highcharts - 如何在 highcarts 甘特图中为选定的 x 轴标签赋予背景颜色
- python - 如何为 django 多租户应用程序编写测试?
- hl7-fhir - FHIR 分析的 json 格式
- spring-boot - 在tomcat中部署spring boot应用
- javascript - 在 Angular 中动态加载组件
- java - Windows Jenkins 服务 org.eclipse.swt.SWTError:没有更多句柄
- android - 如何在 Kotlin 中访问函数内的局部变量
- sql - 基于 SQL 中的多个元键和值更新列