Python Write File
We can use open() function to write into a file or create a new file.
open() function accepts 2 parameters:
- FileName
- Mode
We have following modes available:
- "x" - Create - will create a file, returns an error if the file exist
- "a" - Append - will create a file if the specified file does not exist
- "w" - Write - will create a file if the specified file does not exist
Take a look at implementations.
# Create a new File, return error if file exists
f = open("sampleFile.txt", "x")
#Create a new file if it doesn't exist, overwrite if exists
f = open("sampleFile.txt", "w")
# Append in existing file, don't overwrite
f = open("sampleFile.txt", "a")
To write anything into file we can use write() method, after writing into file we must close the file.
f = open("sampleFile.txt", "w")
f.write("Overwrite existing if there was any. Or create a new file.")
f.close()
Add more content into file by opening it into append mode.
f = open("sampleFile.txt", "a")
f.write("Add more new content in our existing file.")
f.close()