Python File Handling

← Back to Home


🔹 File Handling in Python – Beginner-Friendly 

In Python, file handling allows us to create, read, write, and delete files. This is useful when you want to store data permanently, such as saving user info, logs, reports, etc.


🔸 Why is File Handling Important?

Without file handling, data disappears when the program ends. With files, we can store and retrieve data even after the program stops.


🔸 Opening a File

Python uses the built-in open() function to open a file.

Syntax:

file = open("filename", "mode")

Mode Description
'r' Read (default)
'w' Write (creates new or overwrites file)
'a' Append (adds to end of file)
'x' Create (fails if file exists)
'b' Binary mode (e.g., 'rb', 'wb')

🔸 Example 1: Writing to a File


file = open("example.txt", "w")  # Open in write mode
file.write("Hello, this is a test.\n")
file.write("Writing to a file in Python.\n")
file.close()  # Always close the file!

📝 This creates a file named example.txt and writes two lines to it.


🔸 Example 2: Reading from a File

file = open("example.txt", "r")  # Open in read mode
content = file.read()
print(content)
file.close()

📝 This reads and prints the contents of example.txt.


🔸 Example 3: Appending to a File

file = open("example.txt", "a")  # Open in append mode
file.write("Adding a new line.\n")
file.close()

📝 This adds a new line at the end of the file without deleting the old content.


🔸 Reading Line by Line

file = open("example.txt", "r")
for line in file:
    print(line.strip())      # Here, strip() removes newline characters
file.close()

🔸 Using with Statement (Recommended)

Python provides a cleaner way to handle files using the with statement. It automatically closes the file.

Example:

with open("example.txt", "r") as file:
    data = file.read()
    print(data)

Using this way, you don’t need to call file.close().


🔸 Deleting a File

You can delete a file using the os module.

import os

if os.path.exists("example.txt"):
    os.remove("example.txt")
    print("File deleted.")
else:
    print("File does not exist.")

🔚 Summary

  • Use open() to work with files.

  • Modes: 'r' (read), 'w' (write), 'a' (append), 'x' (create).

  • Always close the file after use (or use with).

  • Use the os module for file operations like deleting or checking existence.


✅ Quick Tip:

Use with open(...) as f: whenever possible—it’s safer and cleaner.

No comments:

Post a Comment

Featured Post

Add Keyboard Shortcuts to Tkinter GUI – Python Hotkeys with Bind Examples

  ← Back to Home ⌨️ Bonus Part 5: Keyboard Shortcuts & Hotkeys in Tkinter – Boost App Productivity 📘 Overview Keyboard shortcuts ...

Popular Posts