Python Write/Create Files ✍️
Writing to Files
To write to a file, use the open() function with mode "w" (write) or "a" (append).
📓 Analogy: The Notebook
- Append ("a"): Like turning to a new page in your notebook and continuing to write. The old notes stay there.
- Write ("w"): Like erasing the ENTIRE notebook and starting fresh on page 1. Be careful!
✨ Append ("a")
Appends content to the end of the file. Does NOT delete existing content.
python
with open("demofile.txt", "a") as f:
f.write("This text is appended.")🔄 Overwrite ("w")
Overwrites the entire file. All previous content is lost!
python
with open("demofile.txt", "w") as f:
f.write("I have deleted the content!")🎯 Real-World Application: Exporting Data
Writing user data to a CSV file for Excel.
python
users = ["Alice,25", "Bob,30", "Charlie,35"]
with open("users.csv", "w") as f:
f.write("Name,Age\n") # Header
for user in users:
f.write(user + "\n")🆕 Create New File ("x")
Creates a new file. Returns an error if the file already exists.
python
try:
with open("myfile.txt", "x") as f:
f.write("New file created!")
except FileExistsError:
print("File already exists.")💡 Writing Lists
You can write a list of strings to a file using writelines().
python
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("demofile.txt", "w") as f:
f.writelines(lines)