Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create fake text file in Python

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.

like image 826
user1454693 Avatar asked Aug 06 '12 17:08

user1454693


People also ask

How do you create a file if not exist in Python?

To create a file if not exist in Python, use the open() function. The open() is a built-in Python function that opens the file and returns it as a file object. The open() takes the file path and the mode as input and returns the file object as output.


1 Answers

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

like image 155
Danica Avatar answered Sep 22 '22 08:09

Danica