Home > Enterprise >  create sub folders while uploading files to Amazon S3
create sub folders while uploading files to Amazon S3

Time:10-22

Previously, I was uploading files to Amazon S3 like this and it worked fine:

bucket.upload_fileobj(
            io.BytesIO(gzipped_content),
            fileName2,
            ExtraArgs={"ContentType": "text/plain"})

In this case, fileName2 was placed directly into the bucket's root folder. Now I want to place fileName2 in sub folders. Like this: bucket/year/month/day/fileName2. I have variables year/month/day saved as strings with me. I tried this:

bucket.upload_fileobj(
            io.BytesIO(gzipped_content),
            year/month/day/fileName2,
            ExtraArgs={"ContentType": "text/plain"})

but this throws an error that: unsupported operand type(s) for /: 'str' and 'str'. I also tried this:

path = year   month   day   fileName2
bucket.upload_fileobj(
            io.BytesIO(gzipped_content),
            path,
            ExtraArgs={"ContentType": "text/plain"})

but in this case, the path appears as the full filename. Instead of sub-folders. How can I use variables to upload files into subfolders? I can't hard code because I will need to run the function in a loop

CodePudding user response:

you need to interpolate the path / key as a string:

bucket.upload_fileobj(
        io.BytesIO(gzipped_content),
        f"{year}/{month}/{day}/{fileName2}",
        ExtraArgs={"ContentType": "text/plain"})

CodePudding user response:

You can construct the key using numerous string interpolation features, including Python f-strings:

f"{year}/{month}/{day}/{fileName2}"
  • Related