To write to an existing file, you must add a parameter to the open() function. You can either append content to the end of the file or completely overwrite it.
"a" - Append: Appends text to the end of the file."w" - Write: Overwrites any existing content in the file."a")Using "a" will add text to the existing file without erasing what's already there.
// Open the file and append a line
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
// Open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
"w")Using "w" will completely erase the old content and replace it with your new content.
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
To create a new file in Python, use the open() method with one of the following parameters:
"x" - Create: Creates a brand new file. If the file already exists, the operation fails and throws an error."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.
# Create a brand new, empty file
f = open("myfile.txt", "x")
Which mode should you use to add text to the end of a file without destroying the current text?