Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps:
- Open file
- Perform operation
- Close file
There are four basic modes in which a file can be opened― read, write, append, and exclusive creations. In addition, Python allows you to specify two modes in which a file can be handled― binary and text. Binary mode is used for handling all kinds of non-text data like image files and executable files.
Python stores files in the form of bytes on the disk. So, when a file is opened in text mode, these files are decoded from bytes to return string objects. While files opened in binary mode return contents as bytes objects (sequences of single bytes) without any decoding. Let us see how to write bytes 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.
In the above example, we opened a file in binary write mode and then wrote some bytes contents as bytes in the binary file.
Alternatively, open() and close() can be called explicitly as shown below. However, this method requires you to perform error handling yourself, that is, ensure that the file is always closed, even if there is an error during writing. So, using the “with” statement is better in this regard as it will automatically close the file when the block ends.
Also, some_bytes can be in the form of bytearray which is mutable, or bytes object which is immutable as shown below.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course