What is StringIO in python used for in reality?

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

    I've used it in place of text files for unit-testing.

    For example, to make a csv 'file' for testing with pandas (Python 3):

    import io
    f = io.StringIO("id,name\n1,brian\n2,amanda\n3,zoey\n")
    df = pd.read_csv(f) # pandas takes a file path or a file-like object
    

    From the documentation here:

    An in-memory stream for text I/O. The text buffer is discarded when the close() method is called.

    The initial value of the buffer can be set by providing initial_value.

    method getvalue(): Return a str containing the entire contents of the buffer.

提交回复
热议问题