Skip to content

Commit 4882d24

Browse files
committed
add optional download_using_prefix to center all downloads in one folder
1 parent 5722e0b commit 4882d24

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

amazon_s3/s3reader.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ def __init__(
6262
alternative_document_service: Optional[Dict[str, str]] = None,
6363
detect_file_duplication: Optional[bool] = False,
6464
skip_storage_download: Optional[bool] = False,
65+
download_using_prefix: Optional[bool] = False,
6566
**kwargs: Any,
6667
) -> None:
6768
"""Initialize S3 bucket and key, along with credentials if needed.
@@ -138,6 +139,7 @@ def __init__(
138139

139140
self.verbose = verbose
140141
self.download_dir = download_dir if download_dir else tempfile.mkdtemp()
142+
self.download_using_prefix = download_using_prefix
141143
if not os.path.exists(self.download_dir):
142144
os.makedirs(self.download_dir)
143145

@@ -558,15 +560,20 @@ def get_files(self) -> list[str]:
558560
return file_paths
559561

560562

561-
def download_s3_file(self, key: str, temp_dir: str, file_paths: list):
563+
def download_s3_file(self, prefix_key: str, temp_dir: str, file_paths: list):
562564
"""Download a single file"""
563565
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/download_file.html#S3.Client.download_file
566+
key = prefix_key
567+
original_key = key
568+
bucket = self.bucket
569+
if self.prefix and self.download_using_prefix is False:
570+
key = key.replace(f"{self.prefix}/", "")
564571
filepath = f"{temp_dir}/{key}"
565572
folder_path = os.path.dirname(filepath)
566573
os.makedirs(folder_path, exist_ok=True)
567-
original_key = key
574+
568575
try:
569-
self.s3.meta.client.download_file(self.bucket, original_key, filepath)
576+
self.s3.meta.client.download_file(bucket, original_key, filepath)
570577
file_paths.append(filepath)
571578
logging.getLogger().debug(f" {original_key} to {key}")
572579
except Exception as e:

0 commit comments

Comments
 (0)