简体   繁体   中英

How to append a string in beginning of each line in file

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM