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()
Answer from Petr Viktorin on Stack OverflowIt'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()
StringIO gives you file-like access to strings, so you can use an existing module that deals with a file and change almost nothing and make it work with strings.
For example, say you have a logger that writes things to a file and you want to instead send the log output over the network. You can read the file and write its contents to the network, or you can write the log to a StringIO object and ship it off to its network destination without touching the filesystem. StringIO makes it easy to do it the first way then switch to the second way.
I've just started back at learning Python so tried to modify an old webscrape I wrote in order to not use physical files, I found online StringIO which seemed perfect.
However, when substituting StringIO in place of open() I can't quite figure out where I've gone wrong.
It seems my loop just overwrites the string rather than creating the list it does with a physical file.
Screenshots of outputs
Any pointers would be greatly appreciated
Hi r/Python ,
I'm working on a project and want to determine the best internal interface. I know io.BytesIO/StringIO has a file like interface that's compatible with most method that takes a file pointer.
Does io.BytesIO/StringIO behave like files when created with in-memory bytes/str? In a scene that a large file is divided into numbers of logical blocks. It will only read the current block into memory when necessary and write back unnecessary block to disk under memory pressure. I know this caching behavior is done by the kernel, does python do this with io.BytesIO/StringIO?
I'm asking this because the real implementation is hiding under this funny _io module that I have no access to.
from _io import (DEFAULT_BUFFER_SIZE, BlockingIOError, UnsupportedOperation,
open, FileIO, BytesIO, StringIO, BufferedReader,
BufferedWriter, BufferedRWPair, BufferedRandom,
IncrementalNewlineDecoder, TextIOWrapper)Thanks,