[英]Upload csv in AWS S3 using “upload_file” get 0 byte in S3
我想在我的 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')
但是我在完成我的 CSV 之前執行了upload_csv()
,正確的方法是將我的上傳 function 移出塊:
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')
我知道愚蠢的錯誤:),但是這個 append ......
希望此編輯將來可以避免此類問題;)
感謝大家,嘗試解決我的問題
這是使用 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.