Using Other Methods to Open and Read Member Files
Other Methods of Opening and Reading Member Files. If you are looking for a more flexible way to read from member files and create and add new member files to an archive, then
.open() method is for you. Like the built-in
open() function, this method implements the context manager protocol, and therefore it supports the
You can also use
.open() with the
"w" mode. This mode allows you to create a new member file, write content to it, and finally append the file to the underlying archive, which you should open in append mode.
The second part of the code confirms that
new_hello.txt is now a member file of
sample.zip. A detail to notice in the output of this example is that
.write() sets the
Modified date of the newly added file to the
1980-01-01, which is a slightly unusual behavior that you should keep in mind when using this method.
There are at least two ways to do this. You can use
ZipFile.read() returns the content of the target member file as bytes,
.decode() can operate on these bytes directly. The
.decode() method decodes a
bytes object into a string using a given character encoding format.
However, you could use any other valid encoding, such as UTF-16 or cp1252, which can be represented as case-insensitive strings. Note that
"utf-8" is the default value of the
encoding argument to
Just as with
io.TextIOWrapper class takes an
encoding argument. You should always specify a value for this argument because the default text encoding depends on the system running the code and may not be the right value for the file that you are trying to decode.
Become a Member to join the conversation.