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
- Raw IO disables buffering. Buffering is the process of reading or writing bytes in chunks of defined block sizes from/to the disk so as to improve the performance of the file I/O. However, there are circumstances that require reading/writing a number of bytes immediately to disk without buffering. Raw I/O provides this unbuffered file I/O.
- 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, (If size of the buffer alone needs to be configured it can be achieved by providing a non-zero integer to the parameter buffering in the open() function call) how many buffers should operate from behind, different buffer sizes and threads for write and read buffers and many other design strategies are addressed.
- By specifying buffering=0 in the open() function call a file is opened in raw mode.
|
logFile = open('appevents.log', 'wb+', buffering=0) |
- When a file is opened for writing in raw mode, the open() function returns a FileIO object on which the write() methods are called.