In this code snippet (authored by another person), self.archive
is a path to a large file and raw_file
is the contents of the file read as binary data.
with open(self.archive, "rb") as f: f.seek(offset) raw_file = start + f.read(dlen - len(start)) ... f.write(raw_file)
This archive file contains stored image files, and I'd like to access them pygame.image.load
which requires a File object. But I need to do something like pygame.image.load(toVirtualFileObject(raw_file))
(i.e. access this archive file's contents as File objects without writing to disk first).
Can this be done?
First, open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.
Writing to a Binary File Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing. Unlike text files, binary files are not human-readable.
HTTP is perfectly capable of handling binary data: images are sent over HTTP all the time, and they're binary. People upload and download files of arbitrary data types all the time with no problem.
To create a file object in Python use the built-in functions, such as open() and os. popen() . IOError exception is raised when a file object is misused, or file operation fails for an I/O-related reason. For example, when you try to write to a file when a file is opened in read-only mode.
This is what StringIO
(in Python 2) and io.BytesIO
in (in Python 3) are for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With