Home »
Python
How to write in an existing file in Python?
In this tutorial, we are going to learn how to write text in an existing file in python?
Submitted by IncludeHelp, on December 28, 2018
As we have discussed in previous post (Opening, closing a file/open(), close() functions in Python), that there are a set of file opening modes.
To write in an existing file - We have to open the file in append mode ("a"), if file does not exist, file will be created.
So, to write text in an existing file, first of all confirm that file exists or not? If the file does not exist, program will create a new file.
Example:
In this example, we will create a file first, write a text and then close the file. And then, we will open the file in append mode ("a").
# write content in an existing file
# first of all, we are creating a file
# and writing some of the data
fo = open("file1.txt", "wt")
fo.write("Hello world.")
fo.close()
# now opening the file in append mode
fo = open("file1.txt","at")
fo.write("How are you?")
fo.close()
# reading and displaying conetnt of the file
# opening the file in read only mode
fo = open("file1.txt","rt")
print("File's content...")
dummy = fo.read()
print(dummy)
fo.close()
Output
File's content...
Hello world.How are you?