Python allows you to create, write, and append to files so that data can be stored permanently on disk. Using different file modes ("w", "a", "x") you can control whether a file is created, overwritten, or extended with new content.
"w" (write), "a" (append), "x" (create).with): automatically opens and safely closes the file.\n): used to move to a new line in the file.? Common modes
"w" – Create a new file or overwrite if it already exists."a" – Append data at the end of an existing file (create if not present)."x" – Create a new file; raises an error if the file already exists.⚙️ Basic syntax
open(filename, mode) returns a file object.with open(...) as f: ensures the file is closed automatically.\n when you want text on a new line in the file.
# Open a new file in write mode (overwrites if it exists)
with open("newfile.txt", "w") as file:
# Write the first line with a newline character
file.write("Hello, World!\n")
# Write the second line without adding an extra newline
file.write("This is a new file.")
# Open the file in append mode to add new content at the end
with open("newfile.txt", "a") as file:
# Add a new line to the existing file content
file.write("\nAppending a new line.")
# Create a new file only if it does not already exist
file = open("anotherfile.txt", "x") # Raises FileExistsError if file already exists
# Close the file after creating it
file.close()
Use writelines() to write a list of strings to a file in one go.
# Prepare a list of lines, each ending with a newline character
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
# Open the file in write mode and write all lines at once
with open("newfile.txt", "w") as file:
# Write each string from the list into the file
file.writelines(lines)
After the first example ("w" mode), the file newfile.txt will contain:
Hello, World!
This is a new file.
After the append example ("a" mode), the same file will contain:
Hello, World!
This is a new file.
Appending a new line.
Using "x" creates a new file only if it does not already exist. If you run the code again and anotherfile.txt is already present, Python will raise a FileExistsError.
with statement so files are closed automatically, even if an error occurs."a" mode when you want to add content without removing existing data.\n at the end of each line when using write() or writelines().writelines() when you already have data as a list of strings."w" mode — it will overwrite the file completely.quotes.txt and write your favorite quotes, one per line.quotes.txt without removing the existing content.\n) from 1 to 10 and write them to numbers.txt using writelines()."x" mode and observe what happens when the file already exists.