How to create fake text file in Python

user1454693 picture user1454693 · Aug 6, 2012 · Viewed 11.1k times · Source

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.

Answer

Danica picture Danica · Aug 6, 2012

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