gpt4 book ai didi

python - 是否可以循环遍历 Amazon S3 存储桶并使用 Python 计算其文件/ key 中的行数?

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:29 31 4
gpt4 key购买 nike

是否可以循环遍历 Amazon S3 存储桶中的文件/ key ,读取内容并使用 Python 计算行数?

例如:

  1. My bucket: "my-bucket-name"
2. File/Key : "test.txt"

我需要遍历“test.txt”文件并计算原始文件中的行数。

示例代码:

for bucket in conn.get_all_buckets():
if bucket.name == "my-bucket-name":
for file in bucket.list():
#need to count the number lines in each file and print to a log.

最佳答案

使用 boto3 您可以执行以下操作:

import boto3

# create the s3 resource
s3 = boto3.resource('s3')

# get the file object
obj = s3.Object('bucket_name', 'key')

# read the file contents in memory
file_contents = obj.get()["Body"].read()

# print the occurrences of the new line character to get the number of lines
print file_contents.count('\n')

如果要对存储桶中的所有对象执行此操作,可以使用以下代码片段:

bucket = s3.Bucket('bucket_name')
for obj in bucket.objects.all():
file_contents = obj.get()["Body"].read()
print file_contents.count('\n')

这里是对 boto3 文档的引用以获得更多功能:http://boto3.readthedocs.io/en/latest/reference/services/s3.html#object

更新:(使用 boto 2)

import boto
s3 = boto.connect_s3() # establish connection
bucket = s3.get_bucket('bucket_name') # get bucket

for key in bucket.list(prefix='key'): # list objects at a given prefix
file_contents = key.get_contents_as_string() # get file contents
print file_contents.count('\n') # print the occurrences of the new line character to get the number of lines

关于python - 是否可以循环遍历 Amazon S3 存储桶并使用 Python 计算其文件/ key 中的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37519061/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com