Python open file append: In this article, we will discuss the topic of how to append in a python file.
Before we fully understand this topic we have to be clear about some basic abbreviations that we use during file handling in python whether we have to write something to the file or append to the file.
There are some modes in python that we need when we work with python files.
These modes are:-
- Read Mode (‘r’)-This is the default mode. This mode opens a file for reading and gives an error if the file doesn’t exist.
- Append mode (‘a’)- This mode is used to append to a file in python. If no file exists it creates a new file.
- Write mode (‘w’)- This mode is used to write to a file in python. If no file exists it creates a new file.
- “r+”: This mode is used for both reading and writing.
- “a+”: This mode is used for both reading and appending.
Difference between writing and appending in a file
Python file append: So some may have a sort of confusion about what is the difference between appending and writing to a file. The basic difference between both of them is that when we open a file in write mode then as many as the time we perform write operation our original data will be overwritten with new data but when we access the file in append mode it means we append new data with original data.
open() function and its working
Python file append: As we know to perform any operation in a file first we have to access it.Here open() function comes into use.the open() function is used to open a file in reading or write or append mode. As our main concern in this topic is to discuss append data so we use append mode with the open() function.
the open() function takes two arguments first is the file name and another is the mode in which we want to access the file. If we do not pass any mode it will by default take ‘r’ mode.
So the syntax is open(fileName,mode).
To open files in append mode we use either ‘a’ mode or ‘a+’ mode. With file access mode ‘a’ open() function first checks if a file exists or not. If a file doesn’t exist it creates a file and then opens it otherwise it directly opens the file. In both cases, a file object is returned.
Syntax: file_object=open(fileName,’a’). Or file_object=open(fileName,’a+’).
Here we can use any variable name. “file_object” is not a compulsion. In file_object a file object is returned which is helpful to perform append operation in the file.
- Python open() Function with Examples
- Python Program to Append the Contents of One File to Another File
- Python Interview Questions on File Manipulation
Python append to file: Here we see a word file object multiple times so let’s understand what file object actually means. The file object is the connector between us and the file. It allows us to read and write in the file. It takes a reference of the file and opens it in the different mode we want.
f=open("append_file.txt", "a") f.write("First Line\n") f.write("Second Line") f.close()
First Line Second Line
Note: \n is used to append data to a new line otherwise our content will look like this…
Output without using “\n” is given below
First LineSecond Line
Python write line to file append: We opened the file ‘append_file.txt’ in append mode i.e. using access mode ‘a’. As the cursor was pointing to the end of the file in the file object, therefore when we passed the string in the write() function, it appended it at the end of the file. So, our text ‘Second Line’ gets added at the end of the file ‘append_file.txt’.
Append Data to a new line in python files
Python write to file append: In the previous example, we see that we use escape sequence ‘\n’ to append data in a new line. This method is good but it will fail in one scenario. When a file does not exist or is empty then this approach will create a problem. Hence we should change this approach and work on a new approach that will work on all the cases.
Before understanding the new approach we must need to know about some abbreviations and functions.
- Read() function: The read() method returns the specified number of bytes from the file. Default is -1 which means the whole file.
For Example, if we write f.read(30) so it will read() first 30 characters from the file.
- seek() method: The seek() method sets the file’s current position at the offset. The whence argument is optional and defaults to 0, which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file’s end.
Note: If the file is only opened for writing in append mode using ‘a’, this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode ‘a+’).
As we understand two important concepts now we will be comfortable in implementing the new approach to append data in a new line in the file.
- Open the file in append & read mode (‘a+’). Both read & write cursor points to the end of the file.
- Move the red cursor to the start of the file.
- Read some text from the file and check if the file is empty or not.
- If the file is not empty, then append ‘\n’ at the end of the file using the write() function.
- Append a given line to the file using the write() function.
- Close the file
As we check whether our file is empty or not so it will work on all the scenarios.
f=open("append_file.txt", "a+") f.seek(0) data = f.read(100) if len(data) > 0 : f.write("\n") f.write("second line")
Hello Nice meeting you second line
Before appending the string “second line” in the file my file has the content “Hello Nice meeting you” so it will append the second line” in the new line.
Use of with open statement to append text in the python file
How to append to a file in python: With open() do similar functions as open() do but one difference is that we do not need to close files. with open() statement handles it.
With open(file,a) as f is similar as f=open(file,a)
with open("append_file.txt","a") as f: f.write("First Line\n") f.write("Second Line")
First Line Second Line
We clearly see that the output is the same as the previous one.
Appending List of items in the python file
Till now we see that we can append text in a file with help of the write() function. But consider a scenario where we have a list of items instead of string then what we can do. One of the traditional ways is that we can run a loop and append data. But there is also another way in which we can append a list of items in a single line without using a loop. We can do this by using writelines() method.
l=['I ','use ','writelines()','function'] f=open("append_file.txt", "a") f.write("First Line\n") f.write("second line\n") f.writelines(l)
First Line second line I use writelines()function
Here we see that we have a list l and we easily append items of the list in the file without using any loop.