简体   繁体   English

在python中 将文件列表转换为类似对象的文件

[英]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? 所以我的问题是,是否有适当的,pythonic的方式将字符串列表转换为类似对象的文件?

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. 我相信第二部分所需要的只是在对象之类的文件上调用“ read()”,因此我还可以使用read作为方法定义一个新类,该类返回一个长字符串,该字符串是所有行字符串。

thanks, -nick 谢谢,-尼克

StringIO implements (nearly) all stdio methods. StringIO实现(几乎)所有stdio方法。 Example: 例:

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

cStringIO is a faster counterpart. cStringIO是一个更快的副本。

To convert your list of string, just join them: 要转换您的字符串列表,只需join它们join

>>> 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 您可以在列表上使用StringIO和str.join,即

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

assuming lines is your list of lines 假设行是您的行列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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