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.
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.
This is exactly what StringIO
/cStringIO
(renamed to io.StringIO
in Python 3) is for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With