nick maxwell
nick maxwell

Reputation: 1509

in python; convert list of files to file like object

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

Upvotes: 2

Views: 4180

Answers (1)

miku
miku

Reputation: 188114

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'

Upvotes: 12

Related Questions