YouTip LogoYouTip

Python3 File Writelines

# Python3.x Python3 File writelines() Method [![Image 3: Python3 File(Files) Method](#) Python3 File Methods](#) * * * `writelines()` is a method of file objects in Python, used to write a list of strings (or any iterable) to a file. Unlike the [write()](#) method, `writelines()` can write multiple lines of content at once, but it does not automatically add newline characters. To add newlines, you must specify the newline character `n`. ### Syntax The syntax for the `writelines()` method is as follows: fileObject.writelines( ) ### Parameters * **`fileObject`**: The file object, typically obtained by opening a file using the `open()` function. * **`sequence`**: An iterable (such as a list, tuple, etc.), where each element must be a string. * **Return Value**: No return value (returns `None`). The `writelines()` method writes all strings from the iterable into the file sequentially. The position where writing occurs depends on the current file pointer position: * If the file is opened in append mode (`"a"` or `"a+"`), the written content will be added to the end of the file. * If the file is opened in read-write mode (`"r+"` or `"w+"`), the written content will overwrite existing content starting from the current file pointer position. ### Return Value This method does not return a value. ### Example The following example demonstrates the use of the `writelines()` method: ## Example #!/usr/bin/python3 # Use the with statement to open the file, ensuring it is properly closed with open("test.txt","w")as fo: print("File name: ", fo.name) seq =[" 1n"," 2"] fo.writelines(seq) The output of the above example is: File name: test.txt View file content: $ cat test.txt 1 2 ### Notes 1. **Does not automatically add newline characters**: * `writelines()` does not automatically add a newline character at the end of each line. If you need newlines, you must explicitly add `n` in each string. 2. **File Mode**: * If the file is opened in read-only mode (`"r"`), calling `writelines()` will raise an `io.UnsupportedOperation` exception. * If the file is opened in write mode (`"w"` or `"w+"`), the file content will be cleared before writing new content. * If the file is opened in append mode (`"a"` or `"a+"`), the written content will be added to the end of the file. 3. **File Pointer**: * The write operation starts from the current file pointer position. If you need to write from the beginning of the file or a specific position, you can use the `seek()` method to move the file pointer. 4. **Iterable**: * `sequence` can be any iterable (such as a list, tuple, generator, etc.), but each element within it must be a string. * * Python3 File Methods](#)
← Python3 Os ChflagsPython3 Os Access β†’