Python has built-in support for performing operations like writing in a file, reading, removing, etc. I have written detailed tutorials covering these file operations:
Reading Text Files Tutorial
How to delete a file in Python
In this tutorial, I am specifically explaining how to write content to a text file using Python.
Without importing any module, you may use the open() function, and depending on the requirements for writing the content, you may specify the mode as explained below.
Modes for opening a file for writing new content
Just to remind you, this is how open() function is used:
In the mode argument, you may specify the writing option as follows:
Option | Description |
w | ‘w’: This value opens the file in write-only mode. Any existing content in the file is truncated and new given content is added. If the file already exists, it is over-written. If the specified file does not exist, it creates a new file. |
a | ‘a’: If you want to keep the existing content and add new content from the end of existing content, use the ‘a’ mode. The value ‘a’ appends the text in the specified text file. |
w+ | ‘w+’: For opening a file in read and write mode, use this value. Just like the ‘w’ value, the ‘w+’ also overwrites the file if it exists. If the file does not exist then creates a new file. |
An example of Python write to file by ‘w’ value
In this example, first I opened the text file with the ‘r’ argument value for mode i.e. opening the text file in read mode to show the existing content.
This is followed by closing the file and reopening in the write mode by using the ‘w’ value.
Again, the file is opened by ‘r’ value, and the content of the file is displayed:
# A demo of writing content to text file ReadTxtFile = open("write-demo.txt", "r") txtContent = ReadTxtFile.read(); print ("Existing Content : ", txtContent) ReadTxtFile.close() #File in write mode WriteTxtFile = open("write-demo.txt", "w") WriteTxtFile.write ("This is new text for the \n demo of writing in text file.") WriteTxtFile.close() #Reopeing file in read mode ReadPostWrite = open("write-demo.txt", "r") ContPostWrite = ReadPostWrite.read(); print ("After write() : ", ContPostWrite) ReadPostWrite.close()
The output:
You can see, the existing content is truncated and new content is added.
The example of write to text file in append mode
So, you do not want to lose existing content and just require adding the new content in the text file. This is where the append mode will work.
For append mode, use the ‘a’ value for the mode argument.
The example below demonstrates how:
# A demo of appending text RTxtFile = open("write-append-demo.txt", "r") txtCont = RTxtFile.read(); print ("Before Append - existing content : ", txtCont) RTxtFile.close() #File in append mode AppendTxtFile = open("write-append-demo.txt", "a") AppendTxtFile.write ("New text in append mode \n added to text file!") AppendTxtFile.close() #Reopeing file in read mode after append ReasPostAppend = open("write-append-demo.txt", "r") ContPostAppend = ReasPostAppend.read(); print ("After Append() : ", ContPostAppend) ReasPostAppend.close()
You can see, the existing content remains in the text file while new content is added at the end of that specified file.
The example of ‘w+’ value with the ‘With’ statement
The ‘with’ keyword is a control flow structure that simplifies the error handling in Python.
In this example, I used the ‘w+’ value for the mode argument; which allows reading and writing operations.
The open function is used in the ‘with’ keyword that itself handles the file closing.
# A demo of w+ with 'With' keyword with open('with-write-demo.txt', 'w+') as fileObject: txtFileCont = fileObject.read() print("Before writing: ", txtFileCont) fileObject.write('The new content is added to the text file!') fileObject.seek(0) #Move pointer at the beginning of text file txtFileCont = fileObject.read() print("After Writing: ", txtFileCont)
The output of above example:
Before writing:
After Writing: The new content is added to the text file!
If file does not exist, a new file is created and as the final call is made for reading the content, it displays only what we wrote by the write() function.
The seek(0) is used to move the pointer at the beginning of the file, otherwise, an empty string is returned.
Using print function for writing in a file
Rather than displaying a line on the screen, you may also write to the file by specifying a file in the print function.
The following example shows writing a line to a text file using the print function:
# Writing by print function with open('print-write.txt', 'w') as objFile: print('Writing a line by print function!', file=objFile)
Similarly, you may append the text by using the ‘a’ value for keeping existing content in the text file.
Writing a list to the text file by writelines() method
So, you may use a list in the writelines() for writing its items in the text file.
# Writing by writelines function fileObject = open("list-write-demo.txt", "w+") lstStrings = ["Python ", "Hello ", "World!"] line = fileObject.writelines( lstStrings ) fileObject.seek(0) #Move pointer at the beginning of text file txtFileCont = fileObject.read() print("After Writing: ", txtFileCont) # Close the file fileObject.close()
The output: