π Python File Handling β Writing & Creating Files
Introduction π
Python makes it easy to create and write files using the built-inopen() function. You can write logs, configs, reports, saved data, or generated content.
Note
π‘ Writing to a file automatically creates it if it doesnβt exist (when using "w", "a", or "x" modes).
1. File Modes for Writing βοΈ
| Mode | Description |
|---|---|
| "w" | Write mode β creates file; overwrites existing content |
| "a" | Append mode β adds new content to end of file |
| "x" | Create mode β creates file; errors if file exists |
| "w+" | Write + Read |
| "a+" | Append + Read |
2. Creating a New File Using "w" Mode π
write_basic.py
with open("notes.txt", "w") as file:
file.write("Hello, Python!\n")
file.write("This is a new file.")β If notes.txt does not exist, Python creates it.
3. Overwriting File Content β οΈ
Note
β "w" deletes all old content before writing.
overwrite.py
with open("notes.txt", "w") as file:
file.write("Overwritten content!")4. Appending to a File Using "a" π
append.py
with open("notes.txt", "a") as file:
file.write("\nNew line added!")β Useful for logs, activity tracking, reports, etc.
5. Creating a File Only If It Doesnβt Exist ("x") π‘οΈ
create_only.py
try:
with open("data.txt", "x") as file:
file.write("New file created!")
except FileExistsError:
print("β File already exists!")β Prevents accidental overwriting.
6. Writing Multiple Lines Using writelines() π§΅
writelines.py
lines = [
"Python is fun!\n",
"File handling is easy.\n",
"This is line 3.\n"
]
with open("multi.txt", "w") as file:
file.writelines(lines)β Make sure each string contains \\n for new lines.
7. Write & Read Using "w+" Mode π
write_read.py
with open("sample.txt", "w+") as file:
file.write("Hello World")
file.seek(0) # Move cursor to start
print(file.read())8. Writing in Binary Mode (Images, PDFs) πΌοΈ
binary_write.py
data = b"Hello in binary"
with open("binfile.dat", "wb") as file:
file.write(data)9. Handling Exceptions When Writing Files π
write_exception.py
try:
with open("/restricted/output.txt", "w") as file:
file.write("Test")
except PermissionError:
print("β You do not have permission to write to this location!")10. Real-World Example: Writing Logs π
log_example.py
import datetime
with open("app.log", "a") as log:
log.write(f"{datetime.datetime.now()} - User logged in\n")11. Real-World Example: Saving User Data π§
user_data.py
user = {"name": "Sathish", "age": 23}
with open("user.txt", "w") as file:
for key, value in user.items():
file.write(f"{key}: {value}\n")12. Real-World Example: Creating Reports π
report.py
report = [
"=== SALES REPORT ===\n",
"Total: $5000\n",
"Profit: $1200\n"
]
with open("report.txt", "w") as file:
file.writelines(report)13. Best Practices π‘
- β Always use with open() to auto-close files
- β Use "a" for logs and history files
- β Use "x" when you want to ensure a file is new
- β Always include newlines (\\n) when writing multiple lines
- β Handle exceptions like FileExistsError & PermissionError
Conclusion π
>>βWriting and creating files unlocks the power to store data, generate reports, save logs, and build real applications.β β¨
You now fully understand Writing & Creating Files in Python! Want the next topic? Try Append Files, File Modes, Delete Files, JSON Handling, or CSV Handling. Just tell me! π