简体   繁体   English

如何在文件中每一行的开头 append 一个字符串

[英]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.我在 s3 上压缩了文件,我必须在其中添加字符串。 I tried following code.我尝试了以下代码。 But it does not append string to first line.但它不会 append 字符串到第一行。

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: str.join在作为参数给出的序列的所有元素之间插入一个常量字符串:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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