Convert list to file object without creating an actual file.

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Jan 24 23:14:16 EST 2008


On Thu, 24 Jan 2008 18:57:58 -0800, Bart  Kastermans wrote:

> I have written a little program that takes as input a text file,
...
> Expected since homeworkhtml is in fact not a file.  Is there a way to
> convert this list to a file object without first writing it to disc and
> then opening the resulting file?

The StringIO module is your friend, together with a couple of basic 
Python techniques.


>>> alist = ["<table>\n", "  <tr>\n", 
... "    <td>", "Nobody expects the Spanish Inquisition!", 
... "</td>\n", "  </tr>\n", "</table>\n"]
>>> print ''.join(alist)  # but strings don't have a readlines method...
<table>
  <tr>
    <td>Nobody expects the Spanish Inquisition!</td>
  </tr>
</table>

>>>
>>> f = StringIO.StringIO()
>>> f.writelines(alist)
>>> f.getvalue()
'<table>\n  <tr>\n    <td>Nobody expects the Spanish Inquisition!</td>\n  
</tr>\n</table>\n'
>>> f.seek(0)  # don't forget to reset the file pointer!
>>> print f.read()  # also has readlines
<table>
  <tr>
    <td>Nobody expects the Spanish Inquisition!</td>
  </tr>
</table>




-- 
Steven



More information about the Python-list mailing list