How to create fake text file in Python

Viewed 13714

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.

3 Answers

In 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

In 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

For more info check docs here

Related