NeutronStar
NeutronStar

Reputation: 2157

Write to a file in Python that's actually a variable?

I have a package I'm using for my research that has a class with a method that writes some information but only writes that information to a file (i.e., the method takes a file object as an argument and as its only argument). However, I need that particular information in my code, not in a file.

My current solution is to have the method write the information to a file like it wants to do and then later open that file and use basic I/O functions to read in the information.

I am wondering, though, is there a way to trick the method into thinking it's writing to a file when it's actually writing to a variable or a list or something? In other words, is there a way I can make a file object that actually points to a variable/list/array/whatever in the code and not to an actual file?

current:

with open('file.txt','w') as f:
    method.write_info(f)

with open('file.txt','r') as f:
    info = f.readlines()

what I want (more or less; I'm just using the same open file syntax as I'm familiar with):

with open(<some sort of variable>) as var_file:
    method.write_info(var_file)

#Then do whatever I want with the information
print <some sort of variable>

Note: I'm using Python 2.7

Upvotes: 0

Views: 152

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

Actually any object that implements the part of the file api used by write_info() will work. Assuming write_info() only uses file.write(), the following would do:

class PseudoFile(object):
    def __init__(self):
        self.content = []

    def write(self, value):
        self.content.append(value)

    def __str__(self):
        return "".join(map(str, self.content))

    def __repr__(self):
        return str(self)


f = PseudoFile()
method.write_info(f)
print f

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599610

You can use a StringIO object as an in-memory buffer that works like a file.

Upvotes: 3

Related Questions