Skip to content

Instantly share code, notes, and snippets.

@kshirsagarsiddharth
Created August 1, 2020 12:15
Show Gist options
  • Select an option

  • Save kshirsagarsiddharth/1d65dd31ab42736e2d0cc65225a551a4 to your computer and use it in GitHub Desktop.

Select an option

Save kshirsagarsiddharth/1d65dd31ab42736e2d0cc65225a551a4 to your computer and use it in GitHub Desktop.
io.StringIO and io.BytesIO
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