Topic 8- File Handling in Python

image 2

Play Store Application link – Java to Python in 17 Steps – App on Google Play

Github project link – https://github.com/kuldeep101990/Python_step8

File handling is a fundamental part of programming. It allows you to read, write, and manipulate files. If you’ve worked with FileReader, BufferedReader, or FileWriter in Java, Python’s file handling will feel familiar yet simpler and more intuitive.


Reading and Writing Files in Python vs. Java

Reading a File

In Java, reading a file typically involves classes like FileReader and BufferedReader.

Java Example:

import java.io.*;
public class Main {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In Python, file reading is much simpler using the with open() construct, which ensures proper resource management.

Python Equivalent:

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

Writing to a File

In Java, writing to a file requires classes like FileWriter or BufferedWriter.

Java Example:

import java.io.*;
public class Main {
    public static void main(String[] args) {
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
            writer.write("Hello, World!\n");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In Python, writing is as simple as specifying the mode (w for write, a for append).

Python Equivalent:

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


File Modes

Python provides several file modes, which determine how the file is opened:

  • r: Read (default mode).
  • w: Write (overwrites the file if it exists).
  • a: Append (adds to the end of the file).
  • rb / wb: Read/Write in binary mode.

Example:

# Reading a file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
# Writing to a file
with open("output.txt", "w") as file:
    file.write("This is a new file.\n")
# Appending to a file
with open("output.txt", "a") as file:
    file.write("Appending this line.\n")


Exception Handling During File Operations

In both Java and Python, file operations can throw errors, like when a file doesn’t exist. Exception handling ensures your program doesn’t crash unexpectedly.

Java Example:

import java.io.*;
public class Main {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("nonexistent.txt"));
            reader.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Python Equivalent:

try:
    with open("nonexistent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found!")
except IOError as e:
    print(f"An error occurred: {e}")


Complete Python Program

Below is a complete Python program demonstrating reading, writing, appending, and exception handling for files.

Python Code:

def main():
    # Writing to a file
    try:
        with open("example.txt", "w") as file:
            file.write("Hello, World!\n")
            file.write("This is a file handling example in Python.\n")
    except IOError as e:
        print(f"Error writing to file: {e}")
    # Reading from a file
    try:
        with open("example.txt", "r") as file:
            print("File content:")
            for line in file:
                print(line.strip())
    except FileNotFoundError:
        print("File not found!")
    except IOError as e:
        print(f"Error reading file: {e}")
    # Appending to a file
    try:
        with open("example.txt", "a") as file:
            file.write("Adding another line.\n")
    except IOError as e:
        print(f"Error appending to file: {e}")
    # Reading again to confirm changes
    try:
        with open("example.txt", "r") as file:
            print("\nUpdated File content:")
            for line in file:
                print(line.strip())
    except IOError as e:
        print(f"Error reading file: {e}")
if __name__ == "__main__":
    main()

How to Run:

  1. Copy the code into a Python file, e.g., file_handling.py.
  2. Run it in your terminal or IDE: python file_handling.py

Sample Output:

File content:
Hello, World!
This is a file handling example in Python.
Updated File content:
Hello, World!
This is a file handling example in Python.
Adding another line.

By comparing Python’s file handling to Java, you can appreciate its simplicity and readability. Try these examples to build your confidence!

Leave a Reply

Your email address will not be published. Required fields are marked *