How to Work with Files in Python (Read, Write, Append) πŸ“‚πŸ

One of the most common tasks in programming is working with files.

Whether you want to read data, save logs, or write configurations, Python makes it very simple.

In this guide, we’ll cover the basics of reading, writing, and appending files in Python β€” step by step.

πŸ“ Opening a File

In Python, you use the open() function.

The syntax is:


python
open("filename", "mode")
"r" β†’ Read (default)

"w" β†’ Write (creates new file or overwrites existing)

"a" β†’ Append (adds to the end of file)

"rb" / "wb" β†’ Read/Write in binary
---
πŸ“– Reading a File
# Open the file in read mode
file = open("example.txt", "r")

# Read the content
content = file.read()
print(content)

# Always close the file!
file.close()
➑️ Or use the with statement (recommended):
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
---
✍️ Writing to a File
with open("example.txt", "w") as file:
    file.write("Hello, Python!n")
    file.write("This will overwrite the file.")
⚠️ Be careful: "w" mode overwrites everything in the file.
---
βž• Appending to a File
with open("example.txt", "a") as file:
    file.write("nThis line was added later.")
βœ… "a" mode keeps old content and just adds new data at the end.
---
πŸ”‘ Quick Summary

Mode            Action

"r"         Read only
"w"         Write (overwrite)
"a"         Append (add new text)
"rb"/"wb"   Binary read/write
---
πŸš€ Final Thoughts
Always close your files (or better, use with open() for safety).

Use "w" carefully β€” it deletes existing data.

Use "a" when you want to add without losing data.

Once you master file handling, you’ll unlock a powerful part of Python for building real-world apps.
---
πŸ’¬ What’s the first project you used file handling for? A text editor? A log system?
Drop your answers below πŸ‘‡

Similar Posts