Python3 File writelines() Method

Python3 File(文件) 方法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.

andwrite()Unlike the write() method, writelines() can write multiple lines at once, but does not automatically add newline characters.

For line breaks, you need to specify newline characters.\n。

Syntax

The syntax of the writelines() method is as follows:

fileObject.writelines( [ sequence ])

Parameters

  • fileObject: The file object, usually obtained byopen()obtained after opening the file with the function.

  • sequence: An iterable object (such as a list, tuple, etc.), each element of which must be a string.

  • Return Value: No return value (returnsNone)。

The writelines() method writes all strings in the iterable to the file sequentially. The write position depends on the current pointer position of the file:

  • If the file is opened in append mode ("a"or"a+") opened, the written content will be appended to the end of the file.

  • If the file is opened in read-write mode ("r+"or"w+") opened, the written content will overwrite existing content starting from the current file pointer position.

Return Value

This method has no return value.

Example

The following example demonstrates the use of the writelines() method:

Example

#!/usr/bin/python3

# Use the with statement to open the file to ensure it is properly closed
with open("test.txt", "w") as fo:
    print("File name: ", fo.name)
    seq = ["Example 1\n", "Example 2"]
    fo.writelines(seq)

The output of the above example is:

文件名为:  test.txt

View file content:

$ cat test.txt 
Example 1
Example 2

Notes

  1. Does not automatically add newline characters:

    • writelines()It does not automatically add newline characters at the end of each line. If line breaks are needed, you must explicitly add them in each string.\n。

  2. File mode:

    • If the file is opened in read-only mode ("r") opened, callingwritelines()will throwio.UnsupportedOperationan exception.

    • If the file is opened in write mode ("w"or"w+") opened, the file content will be cleared, then new content is written.

    • If the file is opened in append mode ("a"or"a+") opened, the written content will be appended 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 useseek()method to move the file pointer.

  4. Iterable object:

    • sequenceIt can be any iterable object (such as a list, tuple, generator, etc.), but each element in it must be a string.


Python3 File(文件) 方法Python3 File Methods

Other extensions