如何使用 boto3 将文件或数据写入 S3 对象

如何使用 boto3 将文件或数据写入 S3 对象

<p>在 boto 2 中,您可以使用以下方法写入 S3 对象:<br /> • <a href="https://boto.readthedocs.io/en/latest/ref/s3.html#boto.s3.key.Key.set_contents_from_string" target="_blank">Key.set_contents_from_string()</a><br /> • <a href="https://boto.readthedocs.io/en/latest/ref/s3.html#boto.s3.key.Key.set_contents_from_file" target="_blank">Key.set_contents_from_file()</a><br /> • <a href="https://boto.readthedocs.io/en/latest/ref/s3.html#boto.s3.key.Key.set_contents_from_filename" target="_blank">Key.set_contents_from_filename()</a><br /> • <a href="https://boto.readthedocs.io/en/latest/ref/s3.html#boto.s3.key.Key.set_contents_from_stream" target="_blank">Key.set_contents_from_stream()</a><br /> 是否有 boto 3 相等的对象? 将数据保存到存储在 S3 上的对象 boto3 方法是什么?</p>
如何使用 boto3 将文件或数据写入 S3 对象 2022-09-01 14:42:12
如何使用 boto3 将文件或数据写入 S3 对象 0
如何使用 boto3 将文件或数据写入 S3 对象
<p>在 boto 3 中,‘Key.set_contents_from_’ 方法被替换为<br /> • <a href="https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Object.put" target="_blank">Object.put()</a><br /> • <a href="https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.put_object" target="_blank">Client.put_object()</a><br /> 例如:</p> <pre><code class="lang-">import boto3 some_binary_data = b'Here we have some data' more_binary_data = b'Here we have some more data' # Method 1: Object.put() s3 = boto3.resource('s3') object = s3.Object('my_bucket_name', 'my/key/including/filename.txt') object.put(Body=some_binary_data) # Method 2: Client.put_object() client = boto3.client('s3') client.put_object(Body=more_binary_data, Bucket='my_bucket_name', Key='my/key/including/anotherfilename.txt') </code></pre> <p>或者,二进制数据可以来自读取文件,如比较 boto 2 和 boto 3 的官方文件中所述:<br /> 存储数据<br /> 从文件、数据流或字符串中存储数据很容易:</p> <pre><code class="lang-"># Boto 2.x from boto.s3.key import Key key = Key('hello.txt') key.set_contents_from_file('/tmp/hello.txt') # Boto 3 s3.Object('mybucket', 'hello.txt').put(Body=open('/tmp/hello.txt', 'rb')) </code></pre>