How to create fake text file in Python

时光毁灭记忆、已成空白 提交于 2019-12-21 03:42:32

问题


How can I create a fake file object in Python that contains text? I'm trying to write unit tests for a method that takes in a file object and retrieves the text via readlines() then do some text manipulation. Please note I can't create an actual file on the file system. The solution has to be compatible with Python 2.7.3.


回答1:


This is exactly what StringIO/cStringIO (renamed to io.StringIO in Python 3) is for.




回答2:


Or you could implement it yourself pretty easily especially since all you need is readlines():

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

then just call it like:

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

That said the other answer is probably more correct.




回答3:


In python3, it can be as simple as

import io
file = io.StringIO("your text goes here") # takes string as arg
file.read()

In python 2.7, it can be something like:

import io
file = io.StringIO(u"your text goes here") # takes unicode as argument
file.read()

You can use the file object for testing purpose.



来源:https://stackoverflow.com/questions/11833428/how-to-create-fake-text-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!