Python: s3 中的递归 glob
Python: recursive glob in s3
我正在尝试从 s3 获取子目录和子目录的子目录(依此类推)内的镶木地板文件路径列表。
如果是我的本地文件系统,我会这样做:
import glob
glob.glob('C:/Users/user/info/**/*.parquet', recursive=True)
我已经尝试使用 s3fs
的 glob
方法,但是它没有递归 kwarg。
是否有我可以使用的功能,或者我需要自己实现吗?
S3 本身实际上没有子目录。
boto3
's S3.Client.list_objects()
支持一个 prefix
参数,它应该让你得到一个给定 "directory" 中的所有对象,无论它们看起来如何 "deep"。
我还想从 s3 存储桶下载最新文件,但位于特定文件夹中。最初,我尝试使用 glob 但找不到解决此问题的方法。最后,我构建了以下函数来解决这个问题。您可以修改此函数以使用子文件夹。
此函数将 return 键值对中所有文件名和时间戳的字典
(键:file_name,值:时间戳)。
只需传递存储桶名称和前缀(即文件夹名称)。
import boto3
def get_file_names(bucket_name,prefix):
"""
Return the latest file name in an S3 bucket folder.
:param bucket: Name of the S3 bucket.
:param prefix: Only fetch keys that start with this prefix (folder name).
"""
s3_client = boto3.client('s3')
objs = s3_client.list_objects_v2(Bucket=bucket_name)['Contents']
shortlisted_files = dict()
for obj in objs:
key = obj['Key']
timestamp = obj['LastModified']
# if key starts with folder name retrieve that key
if key.startswith(prefix):
# Adding a new key value pair
shortlisted_files.update( {key : timestamp} )
return shortlisted_files
latest_filename = get_latest_file_name(bucket_name='use_your_bucket_name',prefix = 'folder_name/')
您可以将 s3fs 与 glob 结合使用:
import s3fs
s3 = s3fs.S3FileSystem(anon=False)
s3.glob('your/s3/path/here/*.parquet')
我正在尝试从 s3 获取子目录和子目录的子目录(依此类推)内的镶木地板文件路径列表。
如果是我的本地文件系统,我会这样做:
import glob
glob.glob('C:/Users/user/info/**/*.parquet', recursive=True)
我已经尝试使用 s3fs
的 glob
方法,但是它没有递归 kwarg。
是否有我可以使用的功能,或者我需要自己实现吗?
S3 本身实际上没有子目录。
boto3
's S3.Client.list_objects()
支持一个 prefix
参数,它应该让你得到一个给定 "directory" 中的所有对象,无论它们看起来如何 "deep"。
我还想从 s3 存储桶下载最新文件,但位于特定文件夹中。最初,我尝试使用 glob 但找不到解决此问题的方法。最后,我构建了以下函数来解决这个问题。您可以修改此函数以使用子文件夹。
此函数将 return 键值对中所有文件名和时间戳的字典
(键:file_name,值:时间戳)。
只需传递存储桶名称和前缀(即文件夹名称)。
import boto3
def get_file_names(bucket_name,prefix):
"""
Return the latest file name in an S3 bucket folder.
:param bucket: Name of the S3 bucket.
:param prefix: Only fetch keys that start with this prefix (folder name).
"""
s3_client = boto3.client('s3')
objs = s3_client.list_objects_v2(Bucket=bucket_name)['Contents']
shortlisted_files = dict()
for obj in objs:
key = obj['Key']
timestamp = obj['LastModified']
# if key starts with folder name retrieve that key
if key.startswith(prefix):
# Adding a new key value pair
shortlisted_files.update( {key : timestamp} )
return shortlisted_files
latest_filename = get_latest_file_name(bucket_name='use_your_bucket_name',prefix = 'folder_name/')
您可以将 s3fs 与 glob 结合使用:
import s3fs
s3 = s3fs.S3FileSystem(anon=False)
s3.glob('your/s3/path/here/*.parquet')