I have zipped file on s3 to which I have to prepend string. I tried following code. But it does not append string to first line.
s3_resource = boto3.resource('s3')
zip_obj = s3_resource.Object(bucket_name=bucket, key=obj_key)
buffer = BytesIO(zip_obj.get()["Body"].read())
try:
z = zipfile.ZipFile(buffer)
for filename in z.namelist():
file1 = z.read(filename).decode("utf-8")
file2 = (processed_dateTimeStr.join(z.read(filename).decode("utf-8").splitlines(True))).encode("utf-8")
object = s3_resource.Object(dest_bucket, f'{dest_fileName}')
object.put(Body=file2)
str.join
inserts a constant string between all elements of the sequence given as argument:
>>> '-'.join(['a', 'b', 'c'])
'a-b-c'
If you want to have it before the first element as well, you can simply use concatenation:
>>> '-' + '-'.join(['a', 'b', 'c'])
'-a-b-c'
... or use a little trick – insert an empty string in the beginning of the sequence:
>>> '-'.join(['', 'a', 'b', 'c'])
'-a-b-c'
In your example, you can use list unpacking to stick with the dense one-liner style:
file2 = (processed_dateTimeStr.join(["", *z.read(filename).decode("utf-8").splitlines(True)])).encode("utf-8")