Writing to Files
Use write mode and append mode to save data to files
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Write mode vs append mode
Open a file in "w" mode to write new content. If the file already exists, Python overwrites it completely.
with open("output.txt", "w") as file:
file.write("Hello, world!\n")Open a file in "a" mode to add content to the end without deleting what is already there.
with open("output.txt", "a") as file:
file.write("Another line.\n")The .write() method
.write() writes a string to the file. It does not add a newline automatically — you must include \n at the end of each line.
file.write("Line 1\n")
file.write("Line 2\n")Confirming a write
Since writing does not produce visible output, always print() a confirmation message so you know the operation succeeded.
Instructions
Write two lines to a file, then append a third line.
- Open
notes.txtin write mode usingwith open("notes.txt", "w") as file:. Inside the block, callfile.write("Line 1: Python is fun\n"), then callfile.write("Line 2: Files are useful\n"). - After the block, call
print("notes.txt created."). - Open
notes.txtin append mode usingwith open("notes.txt", "a") as file:. Inside the block, callfile.write("Line 3: Appended line\n"). - After the block, call
print("notes.txt updated.").
# Step 1: Open notes.txt in write mode and write both lines inside the block # Step 2: Print "notes.txt created." # Step 3: Open notes.txt in append mode and write the third line inside the block # Step 4: Print "notes.txt updated."
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding