'Retrieving last modified file from a subdirectory in AWS s3 using Python

I was trying to get the last modified file from the s3 bucket. I tried different ways to retrieve it. But it always shows me all the files within the directory. Can someone please advice ?

 def last_updated_file(self):
    bucket_name = "test-bucket"
    conn = boto3.session.Session(profile_name="profile-name")
    s3 = conn.resource('s3')
    test_buc = s3.Bucket(bucket_name)
    for x in test_buc.objects.filter(Prefix='test-file/files/'):
        result = x.last_modified
        print("Result is :", result)

The output I am getting is

Result is : 2022-01-18 15:52:48+00:00
Result is : 2022-01-18 15:54:11+00:00
Result is : 2022-01-18 15:54:12+00:00
Result is : 2022-01-24 17:40:24+00:00

I just need the last file which is "2022-01-24 17:40:24+00:00"



Solution 1:[1]

def last_updated_file(self):
bucket_name = "test-bucket"
conn = boto3.session.Session(profile_name="profile-name")
s3 = conn.resource('s3')
test_buc = s3.Bucket(bucket_name)
x = None
for x in test_buc.objects.filter(Prefix='test-file/files/'):
    result = x.last_modified
    print("Result is :", result)
last_modified_file = x.last_modified

This way we can get the last updated file

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 I2Tec