tags:

views:

76

answers:

2

Er, so im juggling parsers and such, and I'm going from one thing which processes files to another.

The output from the first part of my code is a list of strings; I'm thinking of each string as a line from a text file.

The second part of the code needs a file type as an input.

So my question is, is there a proper, pythonic, way to convert a list of strings into a file like object?

I could write my list of strings to a file, and then reopen that file and it would work fine, but is seems a little silly to have to write to disk if not necessary.

I believe all the second part needs is to call 'read()' on the file like object, so I could also define a new class, with read as a method, which returns one long string, which is the concatenation of all of the line strings.

thanks, -nick

+8  A: 

StringIO implements (nearly) all stdio methods. Example:

>>> import StringIO
>>> StringIO.StringIO("hello").read()
'hello'

cStringIO is a faster counterpart.

To convert your list of string, just join them:

>>> list_of_strings = ["hello", "line two"]
>>> handle = StringIO.StringIO('\n'.join(list_of_strings))
>>> handle.read()
'hello\nline two'
The MYYN
Oh great, that does it. I also did it the hard way, which also worked, StringIO looks better. class linesConverter: def __init__(self, input): self.buff = "" for line in input: self.buff += line def read(self, n): a = self.buff[0:n-1] self.buff = self.buff[n:-1] return a
nmaxwell
+3  A: 

You can use StringIO and str.join on your list, i.e.

import StringIO
f = StringIO.StringIO("\n".join(lines))

assuming lines is your list of lines

Ivo van der Wijk