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 30 '21
Idk, you correctly call it a file-like object.
A StringIO object is analagous to what
openreturns, i.e. thefinwith open('myfile') as f.So if you're ok with changing the function, you could just do