YouTip LogoYouTip

Python3 File Write

## Python3 File write() Method The `write()` method in Python writes a specified string to an open file. Depending on the file opening mode, the written content may not appear in the file immediately. It is stored in an internal buffer until the file is closed or the buffer is explicitly flushed using the `flush()` method. --- ### Syntax ```python fileObject.write(string) ``` ### Parameters * **`fileObject`**: The file object, typically obtained by opening a file using the built-in `open()` function. * **`string`**: The string to be written to the file. * **Note**: If the file is opened in binary mode (e.g., `"wb"`, `"ab"`, `"rb+"`), the argument must be a `bytes` object (e.g., by using the `encode()` method on a string). Passing a standard string in binary mode will raise a `TypeError: a bytes-like object is required, not 'str'`. ### Return Value The method returns an integer representing the **number of characters** (or bytes, in binary mode) successfully written to the file. --- ### Behavior and File Pointer Positions The location where the string is written depends on the mode in which the file was opened: * **Append Mode (`"a"` or `"a+"`)**: The content is always appended to the end of the file, regardless of any `seek()` operations. * **Read/Write Mode (`"r+"` or `"w+"`)**: The content is written starting from the current file pointer position, overwriting any existing data at that position. --- ### Code Example Suppose we have a text file named `youtip.txt` with the following initial content: ```text 1:www.youtip.co 2:www.youtip.co 3:www.youtip.co 4:www.youtip.co 5:www.youtip.co ``` The following example demonstrates how to open the file, write a new line to the end, and read back the updated content: ```python #!/usr/bin/python3 # Open the file using a 'with' statement to ensure it is properly closed with open("youtip.txt", "r+") as fo: print("File Name: ", fo.name) # Move the file pointer to the end of the file fo.seek(0, 2) # Write a new line with an explicit newline character fo.write("6:www.youtip.co\n") # Move the file pointer back to the beginning to read the content fo.seek(0) # Read and print all lines for index, line in enumerate(fo): print("Line %d - %s" % (index, line.strip())) ``` #### Output: ```text File Name: youtip.txt Line 0 - 1:www.youtip.co Line 1 - 2:www.youtip.co Line 2 - 3:www.youtip.co Line 3 - 4:www.youtip.co Line 4 - 5:www.youtip.co Line 5 - 6:www.youtip.co ``` #### Updated File Content (`youtip.txt`): ```text 1:www.youtip.co 2:www.youtip.co 3:www.youtip.co 4:www.youtip.co 5:www.youtip.co 6:www.youtip.co ``` --- ### Key Considerations 1. **File Modes**: * **Read-Only Mode (`"r"`)**: Attempting to call `write()` on a file opened in read-only mode will raise an `io.UnsupportedOperation: not writable` exception. * **Write Mode (`"w"` or `"w+"`)**: Opening a file in write mode truncates (empties) the file first. Any existing content will be lost before writing the new content. * **Append Mode (`"a"` or `"a+"`)**: New data is always added to the end of the file. 2. **File Pointer**: * Writing starts at the current file pointer position. If you need to write at a specific position in modes like `"r+"`, use the `seek()` method to reposition the pointer first. 3. **Newlines**: * The `write()` method **does not** automatically append a newline character (`\n`) to the end of the string. You must explicitly include `\n` in your string if you want to start a new line. 4. **Binary vs. Text Mode**: * When writing to a binary file (mode containing `"b"`), you must encode your string to bytes: ```python # Correct way for binary mode fileObject.write("My String".encode('utf-8')) ```
← Python3 Os ChdirPython3 File Readlines β†’