Python program to append a single line to the end of a file:
This post will show you how to append a single line to the end of a file. You will also learn how to append a text with a newline.
Opening a file to append:
To open a file in python, we use the open() method. It takes two parameters, the first one is the file path and the second one is the mode for opening the file. It returns one file object and that object can be used for different file operations.
For appending text to a file, it needs to be open in append mode. Following are the available modes to open a file for appending :
- a : It is used to open a file for appending. If the file doesn’t exist, it creates one new file. The pointer points to the end of the file after open is called.
- a+ : Same as like above. It opens the file for both appending and reading.
- ab : By default, a file is opened in text mode. ab is used to open a file in binary mode.
- ab+ : It also opens a file in binary mode for appending and reading.
Let’s write our first program to append text to a file:
Python program 1: Append text to the end of a file:
We will use a mode for appending text in this example:
given_file = open('input.txt', 'a')
given_file.write('five')
given_file.close()
Here,
- Open the file in append mode, a
- Write the text five to the end.
- close the file.
That’s it. This program is writing on a input.txt file.
For example, if we have one file input.txt with the below content:
one
two
three
four
It will become:
one
two
three
fourfive
Using with open
to open the file:
We can also use with open to open a file in append a mode. The benifit of this method is that we don’t need to close the file as like the above method.
Let’s write the same program using with open :
with open('input.txt', 'a') as given_file:
given_file.write('five')
If you run this program, it will append five to the file input.txt at end.
If the file doesn’t exist:
If the file is not in the path provided, it will create the file and append the text to the start of the file. It will be for any of the above programs.
Similarly, for an empty file, it appends the text to the start of the file. Following are other modes we can use for append:
a : Open the file for append to the end. If the file doesn't exist, it creates one new file.
a+ : Open the file for both appending and reading
ab : Open the file for appending in binary mode
ab+: Open the file for both appending and reading in binary mode
You might also like:
- Python program to remove the first n characters from a string
- How to get all sublists of a list in Python
- Example of python operator module lt
- How to compare one string with an integer value in python
- Python program to read all numbers from a file
- Python program to find the sum of all numbers in a file