What is StringIO in python used for in reality?

前端 未结 8 1527
囚心锁ツ
囚心锁ツ 2021-01-29 20:46

I am not a pro and I have been scratching my head over understanding what exactly StringIO is used for. I have been looking around the internet for some examples. However, almos

8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-29 21:22

    Here's a concrete example of a use case for StringIO: writing some data directly to aws s3, without needing to create a file on local disk:

    import csv
    import io
    import boto3
    
    data = [
        ["test", "data", "headers etc", "123","",],
        ["blah", "123", "35", "blah","",],
        ["abc", "def", "blah", "yep", "blah"]
    ]
    
    bucket_name = 'bucket_name_here'
    session = boto3.Session(
        aws_access_key_id = "fake Access ID"),
        aws_secret_access_key = "fake Secret key"),
        region_name = "ap-southeast-2")
    )
    s3 = session.resource('s3')
    with io.StringIO() as f:
        writer = csv.writer(f, delimiter=",")
        writer.writerows(data)
        resp = s3.Object(bucket_name, "test.csv").put(Body=f.getvalue())
    

    Enjoy your new csv on S3, without having written anything to your local disk!

提交回复
热议问题