I have a function (not mine) which accepts a filename as input, then does things with the file content.
On the other hand, I receive the data which is the "file content" above from somewhere, not as a file.
To illustrate the case, consider the code below.
myfunc()
is something I do not control- the expectation of the authors of
myfunc()
is that the data to process will be in a file ... - ... but I have it as a string
# a function (which I do not control) which uses a filename as input
def myfunc(filename):
with open(filename) as f:
print(f.read())
# case 1: I have a real file
# creation of the file for the sake of the example.
# The authors of myfunc() expect that the the file is just there.
with open("afile.txt", "w") as f:
f.write("hello")
# normal usage of myfunc()
myfunc("afile.txt")
# case 2: I have the contents of the file and need to use myfunc()
# data below is received from somewhere, as a string
data = "world"
# I would like to pass it to myfunc
# ...
How to pass <something>
as the argument of the function so that <something>
holds the content of data
but behaves as a file name?
The obvious solution is to dump data
into a file and pass the filename to myfunc()
. I would like to avoid this intermediate step to keep the whole thing in memory.