How to append a file in Python
This article shows how to append a text file in Python.
Table of contents
P.S Tested with Python 3.8
1. Append to a file
The a
creates a new file or opens an existing file for writing
; the file pointer position at the end of the file
, aka append mode.
file.txt
test 1
test 2
test 3
with open('file-new.txt', 'a') as f:
f.write("a new line") # append this string to the file
Output
file.txt
test 1
test 2
test 3
a new line
2. Difference between a and a+
The a+
adds reading
to the a
mode, aka read append mode.
- The
a
creates a new file or opens an existing file forwriting
; the file pointer position at theend of the file
. - The
a+
creates a new file or opens an existing file forreading and writing
, and the file pointer position at theend of the file
.
2.1 In open mode a
, if we read the file, Python throws io.UnsupportedOperation: not readable
.
with open('file.txt', 'a+') as f:
f.readlines() # read it? `a` mode is only for writing
f.write("a new line") # append this string to the file
Output
Terminal
io.UnsupportedOperation: not readable
2.2 The below example uses a+
to open a file for reading and writing; it read a file, counts the number of lines, and append the result to the file.
file.txt
test 1
test 2
test 3
with open('file.txt', 'a+') as f:
f.seek(0) # a+ file pointer at end, move to beginning
lines = f.readlines()
f.write("\n" + str(len(lines))) # append number of lines to a file
Output
file.txt
test 1
test 2
test 3
3
3. Download Source Code
$ git clone https://github.com/mkyong/python
$ cd io
4. References
About Author
Comments
Subscribe
0 Comments