Write an INI configuration to StringIO
Also published in our Blogger archive.
io.StringIO is a text stream kept in memory, which makes it useful when code needs an INI representation without opening a file. In this example, a ConfigParser receives a service section and two string options. Calling write() serializes the configuration into the StringIO destination, and getvalue() returns the complete generated text for comparison and output.
The assertion includes every newline, including the blank line that ConfigParser.write() places after the section. That makes the output contract explicit: the printed text is exactly [service], followed by the two options and a final blank line. The example also shows that values supplied through the mapping interface are strings, matching the INI parser's storage model.
write() formats a configuration representation; it does not preserve arbitrary input formatting, comments, or every dialect-specific feature of an original file. It also does not validate that localhost and 8080 identify a running service. A caller that writes to disk should choose encoding, replacement, and error-handling policies appropriate to that separate operation. This in-memory example uses Python 3.2+ APIs and no newer API. The ConfigParser documentation documents serialization, while the io documentation describes StringIO as an in-memory text stream.
AI assistance disclosure: This article was drafted with AI assistance and should be adjusted if a consumer requires a different INI layout.
import configparser
from io import StringIO
parser = configparser.ConfigParser()
parser["service"] = {"host": "localhost", "port": "8080"}
destination = StringIO()
parser.write(destination)
rendered = destination.getvalue()
expected = "[service]\nhost = localhost\nport = 8080\n\n"
assert rendered == expected
assert "host = localhost" in rendered
print(rendered, end="")
[service]
host = localhost
port = 8080