🐍 Python File Handling for Beginners

📚 Table of Contents

  • What is File Handling?
  • Opening a File
  • File Modes
  • Reading a File
  • Writing to a File
  • Appending Data
  • Closing a File
  • Practice Examples
  • FAQ

💡 Quick Tip

Always close files after using them to free system resources.

⚠️ Common Mistakes

  • Using wrong file path.
  • Forgetting to close the file.
  • Opening a file in the wrong mode.

✍️ By Roshni Code Charm

📅 July 2026 | ⏱️ 5 min read

📂 What is File Handling?

File handling allows Python programs to create, read, write and manage files. It is used to store data permanently.

📖 Opening a File

The open() function is used to open a file.


file = open("data.txt","r")

print(file.read())

file.close()

✨ File Modes in Python

📖 Reading a File


file = open("student.txt","r")

content = file.read()

print(content)

file.close()

✍️ Writing to a File


file = open("notes.txt","w")

file.write("Python File Handling")

file.close()

➕ Appending Data

Append mode adds new content without deleting old data.


file = open("notes.txt","a")

file.write("\nLearning Python")

file.close()

🔒 Closing a File

The close() method closes the opened file.


file.close()

🚀 Using with Statement

The with statement automatically closes the file.


with open("data.txt","r") as file:

    print(file.read())

📝 Practice Example


with open("message.txt","w") as file:

    file.write("Hello Python")

❓ Frequently Asked Questions

1. Why is file handling used?

File handling is used to save and manage data permanently.

2. Which function opens a file?

The open() function is used to open files.

3. What is the use of close()?

close() is used to close an opened file.