What is StringIO in python used for in reality?

前端 未结 8 1513
囚心锁ツ
囚心锁ツ 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:20

    I've just used StringIO in practice for two things:

    • To unit-test a script that does a lot of printing, by redirecting sys.stdout to a StringIO instance for easy analysis;
    • To create a guaranteed well-formed XML document (a custom API request) using ElementTree and then write it for sending via a HTTP connection.

    Not that you need StringIO often, but sometimes it's pretty useful.

    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题