r/pythonhelp • u/kolinkorr839 • Dec 29 '21
Simulate Opening File Inside Script
I want to be able to simulate opening a file inside a script. This avoids me from creating a physical file. I have this:
import io
fake_file = io.StringIO('''
0 2021-12-21
1 2021-12-20
2 2021-12-19
3 2021-12-18
''')
def get_final_line(filename):
with open(fake_file) as f:
lines = [i for i in f.read().strip().split('\n')]
return lines[-1]
get_final_line('/tmp/test.txt')Originally, I had a physical "/tmp/test.txt", but I am trying to avoid this. So, I saw io.StringIO and according to this, it seems like io.StringIO returns a file-like object? So, I thought it might be possible, when I run this, I get this error:
TypeError: expected str, bytes or os.PathLike object, not StringIOAnyway, what I want is to define a fake_file variable that represents the content of the file, then, later on, have the open function read the fake file as if it is reading a real file. Is this possible?
3
Upvotes
1
u/Goobyalus Dec 29 '21 edited Dec 29 '21
openaccepts the location of something to open, so you would have to mock out theopenfunction itself.You could do something like this:
Output:
Edit: the error is because I accidentally put indentation in the block string, but it illustrates what's happening better lol.