16

如何在 Python 中创建包含文本的假文件对象?readlines()我正在尝试为接受文件对象并通过然后进行一些文本操作检索文本的方法编写单元测试。请注意,我无法在文件系统上创建实际文件。该解决方案必须与 Python 2.7.3 兼容。

4

3 回答 3

34

这正是StringIO/cStringIOio.StringIO在 Python 3 中重命名为)的用途。

于 2012-08-06T17:59:09.080 回答
4

或者你可以很容易地自己实现它,特别是因为你需要的是readlines()

class FileSpoof:
     def __init__(self,my_text):
         self.my_text = my_text
     def readlines(self):
         return self.my_text.splitlines()

然后就这样称呼它:

somefake = FileSpoof("This is a bunch\nOf Text!")
print somefake.readlines()

也就是说,另一个答案可能更正确。

于 2012-08-06T18:09:21.290 回答
3

在 Python3 中

import io
fake_file = io.StringIO("your text goes here") # takes string as arg
fake_file.read() # you can use fake_file object to do whatever you want

在 Python2 中

import io
fake_file = io.StringIO(u"your text goes here") # takes unicode as argument
fake_file.read()  # you can use fake_file object to do whatever you want

有关更多信息,请在此处查看文档

于 2019-11-20T10:40:26.177 回答