πŸ“ 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 ✍️

ModeDescription
"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! 😊