What is StringIO in python used for in reality?

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

    It's used when you have some API that only takes files, but you need to use a string. For example, to compress a string using the gzip module in Python 2:

    import gzip
    import StringIO
    
    stringio = StringIO.StringIO()
    gzip_file = gzip.GzipFile(fileobj=stringio, mode='w')
    gzip_file.write('Hello World')
    gzip_file.close()
    
    stringio.getvalue()
    

提交回复
热议问题