Python File writelines() Method

Example

Open the file in append mode "a" and then add the text list to append to the file:

f = open("demofile3.txt", "a")
f.writelines(["See you soon!", "Over and out."])
f.close()
#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())

Run Example

Definition and Usage

The writelines() method writes the items of the list to the file.

The position of text insertion depends on the file mode and stream position.

"a": Text will be inserted at the current file stream position, by default at the end of the file.

"w": Clear the file before inserting text at the current file stream position (default is 0).

Syntax

file.writelines(list)

Parameter Value

Parameter Description
list The list of text or byte objects to be inserted.

More Examples

Example

As in the above example, but insert a newline for each list item:

f = open("demofile3.txt", "a")
f.writelines(["\nSee you soon!", "\nOver and out."])
f.close()
#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())

Run Example