Modes | Explanation |
---|---|
x | Creates new file ; Returns an error if the file exists |
a | Appends file ; Creates the file if it does not exist |
r | Opens files for reading or error if the file does not exist |
w | Opens and writes in file or creates the file if it does not exist |
To create and write in a new Python file, a new file must be opened first. This is done by using open()
open has Two parameters : the file’s name and the Mode. The mode is how you interact with the file. The example below will Create a new file using the “x” mode
#Here a new File is being created & some context is being written into the file
f = open("newFile.txt", "x")
f.write("Putting content in the file")
f.close()
Here the new file is being read and content will be displayed
f = open("newFile.txt", "r")
print(f.read())
A file’s content can be overwritten by using the “w” mode
f = open("newFile.txt", "w")
f.write("Content was overwritten, here is new data")
f.close()
#here we reopen the file to check if context has changed
f = open("newFile.txt", "r")
print(f.read())
Use “a” to append more context to a file without overwriting a file’s data
f = open("newFile.txt", "a")
f.write("New data was added!")
f.close()
#reopen the file to see the newly added data
f = open("newFile.txt", "r")
print(f.read())