How can you open a file in binary mode in Python?
a) By using the ‘rb’ mode for reading and ‘wb’ mode for writing
b) By using the ‘r’ mode for reading and ‘w’ mode for writing
c) By using the ‘ab’ mode for appending
d) By using the ‘rb+’ mode for reading and writing
Answer:
a) By using the ‘rb’ mode for reading and ‘wb’ mode for writing
Explanation:
To open a file in binary mode in Python, you can use the 'rb'
mode for reading binary files and the 'wb'
mode for writing binary files. Binary mode is used for files that contain binary data, such as images, videos, or any non-text data.
# Example of opening a file in binary read mode
with open("example.bin", "rb") as file:
binary_content = file.read()
# Example of opening a file in binary write mode
with open("example_output.bin", "wb") as file:
file.write(binary_content)
In this example, the file example.bin
is opened in binary read mode, and its contents are read as binary data. The binary data is then written to example_output.bin
in binary write mode.
Opening files in binary mode is essential when working with non-text files, ensuring that the data is handled correctly without any unintended modifications or encoding issues.