Python provides different ways in order to append new data or text into the existing file. The append operation can be done by using the write()
or writelines()
methods. In this tutorial, we examine how to append files in Python.
Open File Append Mode
Python provides two append modes which provide the ability to write
and read and write
. These mods are used during the opening of the file.
- Append only mode:
a
is used as the mode specifier for the open method in order to openh file in append only mode. - Append and Read mode:
a+
is used as the mode specifier for the open method in order to open file read and write mode which also provides the ability to append.
In the following example, we open the file as an append-only mode where we can not read from the file by using the same file handler.
f = open("myfile.txt","a")
In the following example, we open the file as a read and write mode where we can not read from the file by using the same file handler.
f = open("myfile.txt","a+")
Only Append
In this example, we will open the file named “myfile.txt” as only append mode and append some data which is a text. In this mode, we can only append data and can not read the file at the same time.
f = open("myfile.txt","a")
f.write("London")
f.write("Istanbul")
f.close()
Alternatively the writelines()
method can be used to append multiple lines. The writelines() method can accept a list where every item is treated as a line and added as a separate line.
f = open("myfile.txt","a")
lines = ["London","Istanbul","Ankara"]
f.write(lines)
f.close()
Append and Read
As stated previously the append and read mode can be also used to append files. The a+
mode specifier is used to append and read files. In the following example, we use the write()
to append and read()
to read .
f = open("myfile.txt","a")
f.write("London")
f.write("Istanbul")
f.read()
f.close()