Python3 File writelines() Method
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 (returns
None)。
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
# 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
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。
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.
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
seek()method to move the file pointer.
Iterable object:
sequenceIt can be any iterable object (such as a list, tuple, generator, etc.), but each element in it must be a string.
Other extensions
Python3 File Methods