简体   繁体   中英

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

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'

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

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

assuming lines is your list of lines

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM