File output in Python:
Similar to reading contents from files using Python we can also write to files. Python supports three types of input and output. They are
- Text I/O
- Binary I/O
- Raw I/O
The built-in function open() supports writing to file in text, binary and raw formats.
1. Text I/O: Writing to a file in text format
# Example Python program that writes dest = "rhymes.txt" # Now reopen the file in read mode and verify the size |
Output:
Number of bytes to write:156 Numer of bytes verified from file:156 |
2. Binary I/O: Writing binary contents to a file in Python
- When writing in binary mode raw bytes are written to the file without any encodings.
- Binary mode also provides the ability to write at a specified location in a file which is called Random Access. In binary mode it is possible to move the file pointer to a specific location in the file using the seek() method.
- The seek() method is very powerful and is used in applications like database management systems for operations like searching, updating, deleting records and compacting long-used database files and archives. It helps move the file pointer to a specific location and change the contents. While seek() is helpful in allowing to write bytes starting at a specific location care must be taken in calculating the offset dynamically as failing so will lead to data corruption.
Example:
# Example Python program that writes to a file # Define the file path # Open the file in binary write mode # Maintain an index of record vs file position # Account for new line character # Close the file
# Locate the index for a user name and len = 6 print("As a string:") |
Output:
{'User1': 0, 'User2': 6, 'User3': 12, 'User4': 18, 'User5': 24} User name located at:18 As bytes: b'User4\n' As a string: User4 |
3. Raw I/O : Writing raw contents to a file in Python
- If I/O is handled in binary mode, without any buffering - giving the finest control over the I/O stream to the programmer - that is Raw I/O in Python. Raw I/O is provided as a separate mode through the built-in function open().
- A buffer is nothing but a collection of bytes. Though buffering makes it fast by reading blocks of data from hard disk into big chunks, raw mode gives the control to the programmer.
- With Python raw I/O a programmer can always implement a custom buffering mechanism where responsibilities like how a buffer is filled, how much should be the buffer size, how many buffers should operate from behind, different buffer sizes and threads for write and read buffers and many other design strategies are addressed.
Example for Raw I/O in Python:
IndexFileObject = open('index.dat', 'wb+', buffering=0) |
The above snippet will create an index.dat file and write the byte literal into that.