Python - Part - 12 | Python File Handling | በ አማርኛ የ ቀረበ. By ‪@EmmersiveLearning #python ‬#file

3 min read 2 months ago
Published on Dec 16, 2025 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial will guide you through Python file handling, an essential skill for managing and manipulating files in your programs. Understanding file handling will enable you to read from and write to files, making your Python applications more versatile and powerful.

Step 1: Understanding File Handling Concepts

Before diving into code, familiarize yourself with the basic concepts of file handling in Python.

  • File Types: Understand the different types of files you can work with, such as text files (.txt) and binary files.
  • Modes: Learn the modes used to open files:
    • r: Read (default mode)
    • w: Write (overwrites existing file or creates a new one)
    • a: Append (adds to the end of the file)
    • b: Binary mode (for non-text files)

Step 2: Opening a File

Learn how to open a file in Python.

  • Use the open() function:

    file = open('filename.txt', 'r')  # Opens a file in read mode
    
  • Always ensure to close the file after operations using the close() method:

    file.close()
    

Step 3: Reading from a File

Explore various methods to read data from files.

  • Read the entire file:

    content = file.read()
    print(content)
    
  • Read line by line:

    for line in file:
        print(line)
    
  • Read specific number of characters:

    content = file.read(10)  # Reads the first 10 characters
    

Step 4: Writing to a File

Learn how to write data to a file.

  • Open a file in write mode and write data:

    file = open('filename.txt', 'w')
    file.write("Hello, World!")
    file.close()
    
  • Use append mode to add to an existing file:

    file = open('filename.txt', 'a')
    file.write("\nAdding a new line.")
    file.close()
    

Step 5: Using the With Statement

Utilize the with statement for better file handling.

  • This approach automatically closes the file after the block of code:
    with open('filename.txt', 'r') as file:
        content = file.read()
        print(content)
    

Step 6: Exception Handling

Implement error handling to manage file operations safely.

  • Use try and except blocks:
    try:
        with open('filename.txt', 'r') as file:
            content = file.read()
    except FileNotFoundError:
        print("The file does not exist.")
    

Conclusion

In this tutorial, you learned the fundamentals of file handling in Python, including opening, reading, writing, and closing files, as well as utilizing exception handling for robust applications. Practice these skills by creating your own scripts that manipulate text files, and consider exploring more advanced topics like working with JSON files or databases as your next steps.