Created
August 1, 2020 12:15
-
-
Save kshirsagarsiddharth/1d65dd31ab42736e2d0cc65225a551a4 to your computer and use it in GitHub Desktop.
io.StringIO and io.BytesIO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import io | |
| s = io.StringIO() | |
| print(s.write("Hello World/n")) | |
| # ------->Output: 13 | |
| # adding to the memory buffer using print statement | |
| print("adding using the print",file = s) | |
| # get all of the data written in the file | |
| print(s.getvalue()) | |
| # ------>Output: Hello World/nadding using the print | |
| # wrapping a file interface around a string | |
| s = io.StringIO("Hello\nWorld\n") | |
| print(s.readlines()) | |
| # ------>Output: ['Hello\n', 'World\n'] | |
| # StringIO class should be only used for strings | |
| # if we are dealing with bytes we should use BytesIO | |
| s = io.BytesIO() | |
| s.write(b"This is a binary string") | |
| print(s.getbuffer()) | |
| print(s.getvalue()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment