Yes - in Python 3, there is the module io
- and within it, the classes BytesIO
to create what you call "virtual file"(*) binary, and Stringio to do the same with a text file.
Objects in this class have the methods write
, read
, seek
and others to "pretend" that they are a file, and can have all the content that is written on them as a "bytes" (or "str" type object) at any time:
In [68]: from io import StringIO
In [70]: arq = StringIO()
In [71]: arq.write("um monte de texto\n")
Out[71]: 18
In [72]: texto = arq.getvalue()
In [73]: print(texto)
um monte de texto
Classes are made for you to pass an instance of them to code
that expects a file as a parameter - for example, the functions of saving images from the "Pillow" library - and when the function returns, you have access to the bytes that would have been written in a file ". jpg" on disk.
Note that the code that uses the file cannot call the method .close()
on it, otherwise it is not possible to retrieve the content. But if this happens, it’s easy to get around by creating a very simple subclass, which will "turn off" the method close()
putting one who does nothing in place:
In [82]: a = io.BytesIO
In [83]: a = io.BytesIO()
In [84]: a.write(b"teste")
Out[84]: 5
In [85]: a.close()
In [86]: a.getvalue()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-86-a51238acd863> in <module>
----> 1 a.getvalue()
In [89]: class CloseProofIO(io.BytesIO):
...: def close(self):
...: pass
...:
...:
In [90]: b = CloseProofIO()
In [91]: b.write(b"outro teste\n")
Out[91]: 12
In [92]: b.close()
In [93]: b.getvalue()
Out[93]: b'outro teste\n'
(*) I never officially saw the terminology "virtual file" - but I think it can be quite correct. At least I understood the concept at first.
Wouldn’t it just not record the field
url
? The variable would not be the "virtual file"?– anonimo
In case for playback it needs to run the allocated file as . m3u8, direct mode by url does not work
– Gladiston leal
Have you ever thought of forwarding input and output? If your problem is keeping a file written to your disk.
– anonimo
How would that be? can you give an example
– Gladiston leal
https://pt.wikipedia.org/wiki/Redirection_(computes%C3%A7%C3%A3o)
– anonimo
I’ll read it, thank you
– Gladiston leal
People - just to reiterate one consideration: if you can’t understand a question, it might just be because you don’t have the knowledge to answer it yet - avoid negatively asking a question just for that. In this case, for example, the answer is simple and unique in the form of a functionality in the language itself.
– jsbueno