Files that hold photographs, videos, zip files, executable programs, etc. are called binary files: they’re not organized into lines, and cannot be opened with a normal text editor. Python works just as easily with binary files, but when we read from the file we’re going to get bytes back rather than a string. Here we’ll copy one binary file to another:
１ f = open("somefile.zip", "rb")
２ g = open("thecopy.zip", "wb")
４ while True:
５ buf = f.read(1024)
６ if len(buf) == 0:
There are a few new things here. In lines 1 and 2 we added a "b" to the mode to tell Python that the files are binary rather than text files. In line 5, we see read can take an argument which tells it how many bytes to attempt to read from the file. Here we chose to read and write up to 1024 bytes on each iteration of the loop. When we get back an empty buffer from our attempt to read, we know we can break out of the loop and close both the files.
If we set a breakpoint at line 6, (or print type(buf) there) we’ll see that the type of buf is bytes. We don’t do any detailed work with bytes objects in this textbook.