In this article, we will discuss how to append text or new lines to an existing file using python. With file access mode ‘a’, open() function first
checks if file exists or not. If the file doesn’t exist, then it creates an empty file and opens it. Whereas, if the file already exists then it opens it. In both cases, it returns a file object, and it has write cursor, which points to the end of the opened file. Now, if you write anything to the file using this file object, then it will be appended to the end. Let’s use this to append text at the end of a file, Suppose we have a file ‘sample.txt,’ and its contents are, Now let’s append text ‘hello’ at the end of this file, Contents of the file ‘sample.txt’ will be now, We opened the file ‘sample.txt’ in append mode i.e. using access mode ‘a’. As cursor was pointing to the end of the file in the file object, therefore when we passed the string in write() function, it appended it at the end of the file. So, our text ‘hello’ gets added at the end of the file ‘sample.txt’. We can open the file in append access mode i.e. ‘a’, using ‘with open’ statement too, and then we can append the text at the end of the file. # Open a file with access mode 'a' with open("sample.txt", "a") as file_object: # Append 'hello' at the end of file file_object.write("hello") Contents of the file ‘sample.txt’ will be now, Hello this is a sample file It contains sample text This is the end of filehellohello Text ‘hello’ gets again added at the end of file ‘sample.txt’. Advertisements In both the above examples, the text gets added at the end of the file. But as we can see, it is not appended as a new line. There might be scenarios when we want to add data to a file as a new line. Append data to a file as a new line in PythonSolution for this is a little tricky here. let’s start with the basic approach and then we will discuss drawback in it and see how to improve over it, Basic approach
Well this approach works fine if our file already exists and already has some data in it. But if the file doesn’t exist or file is empty then this approach will fail because contents of the file will be like this, …………………….. New added Line It first writes an empty line and then writes our line. But in this case, only appending a line was fine, we don’t need to write ‘\n’ before that. So, our final approach should be like this,
This solution will work fine in both scenarios. Let’s use this solution to append a newline at the end of the file. Suppose we have a file ‘sample2.txt’ with
following contents, Hello this is a sample file It contains sample text This is the end of file Append new line to the file, # Open the file in append & read mode ('a+') with open("sample2.txt", "a+") as file_object: # Move read cursor to the start of file. file_object.seek(0) # If file is not empty then append '\n' data = file_object.read(100) if len(data) > 0 : file_object.write("\n") # Append text at the end of file file_object.write("hello hi") Contents of the file ‘sample2.txt‘ now, Hello this is a sample file It contains sample text This is the end of file hello hi A new line is appended at the end of the file. File access mode ‘a+’, creates opens the file for both read and writing. Also if file it doesn’t exist, and then it creates the file too. Let’s move the code to a separate function, def append_new_line(file_name, text_to_append): """Append given text as a new line at the end of file""" # Open the file in append & read mode ('a+') with open(file_name, "a+") as file_object: # Move read cursor to the start of file. file_object.seek(0) # If file is not empty then append '\n' data = file_object.read(100) if len(data) > 0: file_object.write("\n") # Append text at the end of file file_object.write(text_to_append) Let’s use this function to append one more line to a file that doesn’t exist # Append one line to a file that does not exist append_new_line('sample3.txt', 'This is first line') Contents of the file ‘sample3.txt’ will be now, This is first line It confirms that it didn’t append ‘\n’ before writing a new line because the file was already empty. Now let’s again append another line to the same
file to check if it works fine, # Append another line to a file that already exist & has some contents append_new_line('sample3.txt', 'This is second line') Contents of the file ‘sample3.txt’ will be now, This is first line This is second line As file already exist and has contents too; therefore it first appended the ‘\n’ into the file and then our given line. Append multiple lines to a file in PythonSuppose we have a list of string, list_of_lines = ['First Line', 'Second Line', 'Third Line'] Now we want to append each element in the list as a line in the file. How to do that? We could do that by calling above created function
append_new_line() multiple times, but it is not an optimized solution because it will open and close the file for each element in the list.
Basically we don’t need to write first ‘\n’ if the file is empty. A function to append multiple lines in a file is, def append_multiple_lines(file_name, lines_to_append): # Open the file in append & read mode ('a+') with open(file_name, "a+") as file_object: appendEOL = False # Move read cursor to the start of file. file_object.seek(0) # Check if file is not empty data = file_object.read(100) if len(data) > 0: appendEOL = True # Iterate over each string in the list for line in lines_to_append: # If file is not empty then append '\n' before first line for # other lines always append '\n' before appending line if appendEOL == True: file_object.write("\n") else: appendEOL = True # Append element at the end of file file_object.write(line) Now let’s use this function. This is first line This is second line We have a list of strings, list_of_lines = ['First Line', 'Second Line', 'Third Line'] Append all the strings in this list as separate lines at the end of file ‘sample3.txt’ # Append strings in list as seperate new lines in the end of file append_multiple_lines('sample3.txt', list_of_lines) Now contents of file ‘sample3.txt’ is, This is first line This is second line First Line Second Line Third Line It appended all the strings in the given list as newlines in the file. The complete example is as follows, def append_new_line(file_name, text_to_append): """Append given text as a new line at the end of file""" # Open the file in append & read mode ('a+') with open(file_name, "a+") as file_object: # Move read cursor to the start of file. file_object.seek(0) # If file is not empty then append '\n' data = file_object.read(100) if len(data) > 0: file_object.write("\n") # Append text at the end of file file_object.write(text_to_append) def append_multiple_lines(file_name, lines_to_append): # Open the file in append & read mode ('a+') with open(file_name, "a+") as file_object: appendEOL = False # Move read cursor to the start of file. file_object.seek(0) # Check if file is not empty data = file_object.read(100) if len(data) > 0: appendEOL = True # Iterate over each string in the list for line in lines_to_append: # If file is not empty then append '\n' before first line for # other lines always append '\n' before appending line if appendEOL == True: file_object.write("\n") else: appendEOL = True # Append element at the end of file file_object.write(line) def main(): print('Append a text to file in Python') # Open a file with access mode 'a' file_object = open('sample.txt', 'a') # Append 'hello' at the end of file file_object.write('hello') # Close the file file_object.close() print('Append a text to file in Python using "with statement"') # Open a file with access mode 'a' with open("sample.txt", "a") as file_object: # Append 'hello' at the end of file file_object.write("hello") print('Append data to a file as a new line in Python') # Open the file in append & read mode ('a+') with open("sample2.txt", "a+") as file_object: # Move read cursor to the start of file. file_object.seek(0) # If file is not empty then append '\n' data = file_object.read(100) if len(data) > 0 : file_object.write("\n") # Append text at the end of file file_object.write("hello hi") # Append one line to a file that does not exist append_new_line('sample3.txt', 'This is first line') # Append another line to a file that already exist & has some contents append_new_line('sample3.txt', 'This is second line') print('Append multiple lines to a file in Python') list_of_lines = ['First Line', 'Second Line', 'Third Line'] # Append strings in list as seperate new lines in the end of file append_multiple_lines('sample3.txt', list_of_lines) if __name__ == '__main__': main() Output: Append a text to file in Python Append a text to file in Python using "with statement" Append data to a file as a new line in Python Append multiple lines to a file in Python How do I write content to an existing file in Python?Python File Write. ❮ Previous Next ❯. Example. Open the file "demofile2.txt" and append content to the file: f = open("demofile2.txt", "a") f.write("Now the file has more content!") f.close() ... . Example. Open the file "demofile3.txt" and overwrite the content: f = open("demofile3.txt", "w") f.write("Woops! ... . ❮ Previous Next ❯. How do I edit an existing file in Python?Use writelines() or write() to write to a file in Python
When opening a file to edit with open(file, mode="r") , set mode to "w" to write to a file or "a" to append to the end of a file. Setting mode to w will create the file specified if it does not exist, and overwrite the file if it does exist. Use file.
How do I add lines to an existing file?You do this by using the append redirection symbol, ``>>''. To append one file to the end of another, type cat, the file you want to append, then >>, then the file you want to append to, and press <Enter>.
How do you append a file to another file in Python?Algorithm :. Enter the names of the files.. Open both the files in read only mode using the open() function.. Print the contents of the files before appending using the read() function.. Close both the files using the close() function.. Open the first file in append mode and the second file in read mode.. |