Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treat binary data as a file object?

Tags:

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?

like image 912
SimonT Avatar asked Apr 15 '13 03:04

SimonT


People also ask

How do you write binary data to a file in Python?

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.

What file mode is used in binary files?

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.

How does HTTP transfer binary data?

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.

How do you create a file like an object in Python?

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.


1 Answers

This is what StringIO (in Python 2) and io.BytesIO in (in Python 3) are for.

like image 99
jwodder Avatar answered Oct 14 '22 01:10

jwodder