AWS S3 write an object – TypeError: expected string or bytes-like object

I’m trying to write a simple txt file to S3 using boto3. No matter what I do it would throw the same error. The variable ‘msg’ is a string. In theory it should have been accepted but it did not work. So I encoded it, still doesn’t work. Any ideas? TIA

report = s3.Object(bucket, reportfilename)
byte_msg=bytes(msg, 'utf-8')
s3put = report.put(Body=byte_msg)
Traceback (most recent call last):
  File "/Users/ardey/Google Drive/Tutorials/Python/aws_boto3/s3-interactions.py", line 44, in <module>
    s3put = report.put(Body="""
  File "/Users/ardey/anaconda3/lib/python3.8/site-packages/boto3/resources/factory.py", line 520, in do_action
    response = action(self, *args, **kwargs)
  File "/Users/ardey/anaconda3/lib/python3.8/site-packages/boto3/resources/action.py", line 83, in __call__
    response = getattr(parent.meta.client, operation_name)(*args, **params)
  File "/Users/ardey/anaconda3/lib/python3.8/site-packages/botocore/client.py", line 386, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/Users/ardey/anaconda3/lib/python3.8/site-packages/botocore/client.py", line 677, in _make_api_call
    request_dict = self._convert_to_request_dict(
  File "/Users/ardey/anaconda3/lib/python3.8/site-packages/botocore/client.py", line 723, in _convert_to_request_dict
    api_params = self._emit_api_params(
  File "/Users/ardey/anaconda3/lib/python3.8/site-packages/botocore/client.py", line 752, in _emit_api_params
    self.meta.events.emit(
  File "/Users/ardey/anaconda3/lib/python3.8/site-packages/botocore/hooks.py", line 356, in emit
    return self._emitter.emit(aliased_event_name, **kwargs)
  File "/Users/ardey/anaconda3/lib/python3.8/site-packages/botocore/hooks.py", line 228, in emit
    return self._emit(event_name, kwargs)
  File "/Users/ardey/anaconda3/lib/python3.8/site-packages/botocore/hooks.py", line 211, in _emit
    response = handler(**kwargs)
  File "/Users/ardey/anaconda3/lib/python3.8/site-packages/botocore/handlers.py", line 231, in validate_bucket_name
    if not VALID_BUCKET.search(bucket) and not VALID_S3_ARN.search(bucket):
TypeError: expected string or bytes-like object

Answer

The error is thrown in block if not VALID_BUCKET.search(bucket) and not VALID_S3_ARN.search(bucket)

Per the docs, s3.Object constructor accepts bucket_name (string) and key (string) as arguments. Make sure you’re passing the bucket name as a string and not as a Bucket object.