In this tutorial, you will learn various ways to write text files in Python.
Below is the basic syntax of the open() function:
f = open(file, mode, encoding='utf-8')
You can create a new file or append to existing file content or overwrite the existing content of a file using python with the open method with the appropriate access modifier.
The following are the 3 different modes.
“a” – Append – will append to the end of the file
“w” – Write – will overwrite any existing content
“x” – Create – will create a file, returns an error if the file exists
Append to the existing file.
To append something to a file, use the code snippet as follows:
with open('file.txt', 'a') as f:
f.write("Something\n")
Overwrite the existing file.
To write something to a file and overwrite it:
with open('file.txt', 'w') as f:
f.write("Something\n")
Create a new file and write.
To create a new file and throw an error if the file exists
with open('file.txt', 'w') as f:
f.write("Something\n")