This is a static archive of the Python wiki, which was retired in February 2026 due to lack of usage and the resources necessary to serve it — predominately to bots, crawlers, and LLM companies.
Pages are preserved as they were at the time of archival. For current information, please visit python.org.
If a change to this archive is absolutely needed, requests can be made via the infrastructure@python.org mailing list.

Asking for Help: Is there a way to create a file object from text without touching the file system?

I want to use ElementTree to parse a text object, but the ElementTree.parse function looks like it only takes file objects. I'm doing this all from within Blender, and don't want to touch the filesystem - so is there a way to create a file object from text (to pass to parse) without touching the file system? I'd also like to go the other way, create a text object from an ElementTree object.

Answer

The StringIO module provides support for treating strings like file objects. Since there's a faster version of the module, the idiom to use to access the all-important StringIO class (yes, it has the same name) is as follows:

   1 try:
   2     from cStringIO import StringIO
   3 except ImportError:
   4     from StringIO import StringIO

In fact, for the exact problem you're having, the example "21 lines: XML/HTML parsing (using Python 2.5 or third-party library)" from the SimplePrograms page should at least help you with the parsing problem. For serialising ("going the other way"), you probably want to create a StringIO object and then pass it to the appropriate ElementTree node method.


CategoryAskingForHelp CategoryAskingForHelpAnswered


2026-02-14 16:06