πŸ“‚ Python File Handling
Estimated reading: 3 minutes 96 views

πŸ“ Python File Handling – Read, Write, Append & Manage Files Easily

🧲 Introduction – Why File Handling Matters in Python

Handling files is essential for storing data permanently. Python’s built-in file handling functions make it easy to create, read, update, or delete filesβ€”supporting everything from configuration files and logs to data pipelines.

🎯 What You Will Learn:

  • Opening, reading, and writing files using open()
  • File modes: r, w, a, x, b, t, and +
  • Functions like read(), write(), readlines(), writelines()
  • Exception handling with try...except for file errors

πŸ“‚ 1. Opening and Closing Files

βœ… Using open() Function

file = open("example.txt", "r")
print(file.read())
file.close()

βœ… Explanation:

  • "r" opens the file in read mode.
  • close() frees system resources and ensures changes are saved.

πŸ’‘ Tip: Always close files manually or use a with block for auto-closure.


βœ… Using with Statement (Best Practice)

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

βœ… This ensures the file is closed automatically after the block ends.


🧾 2. File Modes in Python

ModeDescription
'r'Read mode (default). Errors if file doesn’t exist
'w'Write mode. Overwrites or creates new file
'a'Append mode. Adds to existing file or creates new
'x'Create mode. Fails if file exists
'b'Binary mode (e.g., images)
't'Text mode (default)
'+'Read and write combined (e.g., r+, w+)

πŸ“– 3. Reading from Files

βœ… read()

with open("example.txt", "r") as f:
    print(f.read())

βœ… Reads entire file content as a string.


βœ… readline()

with open("example.txt", "r") as f:
    print(f.readline())

βœ… Reads one line at a time.


βœ… readlines()

with open("example.txt", "r") as f:
    lines = f.readlines()
    print(lines)

βœ… Returns a list of lines in the file.


✏️ 4. Writing to Files

βœ… write()

with open("output.txt", "w") as f:
    f.write("Hello, World!\n")

βœ… Writes a string to file. Must add \n for line breaks.


βœ… writelines()

lines = ["Line 1\n", "Line 2\n"]
with open("output.txt", "w") as f:
    f.writelines(lines)

βœ… Writes multiple strings (as list) into file.


βž• 5. Appending to Files

with open("output.txt", "a") as f:
    f.write("New Line\n")

βœ… Adds content at the end without overwriting existing data.


❌ 6. Handling File Not Found Errors

try:
    with open("missing.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("File does not exist.")

βœ… Prevents crash if file is missing by using try...except.


πŸ’‘ Best Practices

  • βœ… Use with open() for safety and simplicity.
  • βœ… Choose correct file mode ('r', 'w', 'a') as per operation.
  • βœ… Use os.path.exists() to check file presence (optional).
  • βœ… Handle exceptions gracefully.

πŸ“Œ Summary – Recap & Next Steps

Python file handling is crucial for working with persistent data sources. From reading logs to writing reports, it simplifies data access and manipulation.

πŸ” Key Takeaways:

  • Use open() with correct modes (r, w, a, x)
  • Use read(), write(), readlines() for I/O
  • Always use with open() to manage files efficiently
  • Handle file-related errors with try...except

βš™οΈ Real-World Relevance:
This is widely used in data logging, report generation, configuration management, and automation.


❓ FAQ – Python File Handling

❓ How do I safely open and close a file in Python?

βœ… Use:

with open("file.txt", "r") as f:
    print(f.read())

This auto-closes the file.

❓ What’s the difference between w and a?

βœ… 'w' overwrites the file; 'a' appends data at the end.

❓ How do I read a file line by line?

βœ… Use readline() or a loop:

with open("file.txt", "r") as f:
    for line in f:
        print(line)

❓ How to handle missing file errors?

βœ… Use try...except FileNotFoundError block.

❓ What’s the difference between text and binary mode?

βœ… 't' is for human-readable text. 'b' is for non-text files like images or audio.


Share Now :
Share

Python File Handling Explained

Or Copy Link

CONTENTS
Scroll to Top