s3_demo.py 848 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import boto3
  2. def upload_file(file_name, bucket):
  3. """
  4. Function to upload a file to an S3 bucket
  5. """
  6. object_name = file_name
  7. s3_client = boto3.client('s3')
  8. response = s3_client.upload_file(file_name, bucket, object_name)
  9. return response
  10. def download_file(file_name, bucket):
  11. """
  12. Function to download a given file from an S3 bucket
  13. """
  14. s3 = boto3.resource('s3')
  15. output = f"downloads/{file_name}"
  16. s3.Bucket(bucket).download_file(file_name, output)
  17. return output
  18. def list_files(bucket):
  19. """
  20. Function to list files in a given S3 bucket
  21. """
  22. s3 = boto3.client('s3')
  23. contents = []
  24. try:
  25. for item in s3.list_objects(Bucket=bucket)['Contents']:
  26. print(item)
  27. contents.append(item)
  28. except Exception as e:
  29. pass
  30. return contents