r/pythonhelp • • 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 StringIO

Anyway, 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

7 comments sorted by

View all comments

Show parent comments

1

u/Goobyalus Dec 30 '21

Idk, you correctly call it a file-like object.

A StringIO object is analagous to what open returns, i.e. the f in with open('myfile') as f.

So if you're ok with changing the function, you could just do

def get_final_line(filename):
    #with open(fake_file) as f:
    f = fake_file
    # The following 2 lines were unindented because we commented out the with
    lines = [i for i in f.read().strip().split('\n')]
    return lines[-1]

2

u/[deleted] Dec 31 '21

I usually replace open with StringIO

with StringIO(filename) as f:

where filename references a multiline string object.

1

u/Goobyalus Dec 31 '21

Huh, I thought I tried this and it didn't work, but I guess I messed it up. Thanks!

u/kolinkorr839 This is much better!

2

u/kolinkorr839 Dec 31 '21

Thank you! This is much more in line with what I wanted.