Reading a File

Java: java import java.io.;

TrackJava to Python Journey
Current SectionPython Basics
Progress14 of 19

1. Reading a File

Reading Entire File

Java:

import java.io.*;

// Method 1: Using BufferedReader
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// Method 2: Using Files class (Java 7+)
import java.nio.file.*;
try {
    String content = new String(Files.readAllBytes(Paths.get("file.txt")));
    System.out.println(content);
} catch (IOException e) {
    e.printStackTrace();
}

// Method 3: Using Scanner
try (Scanner scanner = new Scanner(new File("file.txt"))) {
    while (scanner.hasNextLine()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

Python:

# Method 1: Using context manager (recommended)
try:
    with open("file.txt", "r") as file:
        content = file.read()  # Read entire file
        print(content)
except FileNotFoundError:
    print("File not found")

# Method 2: Read line by line
with open("file.txt", "r") as file:
    for line in file:
        print(line.strip())  # strip() removes newline

# Method 3: Read all lines as list
with open("file.txt", "r") as file:
    lines = file.readlines()  # Returns list with newlines
    for line in lines:
        print(line.strip())

# Method 4: Without context manager (manual cleanup)
file = open("file.txt", "r")
content = file.read()
file.close()

Key Differences:

  • Python uses with statement (context manager) for automatic cleanup.
  • Java requires try-with-resources or manual close().
  • Python's file object is directly iterable.

2. Writing to a File

Java:

import java.io.*;

// Method 1: Using FileWriter
try (FileWriter writer = new FileWriter("output.txt")) {
    writer.write("Hello, World!\n");
    writer.write("Line 2\n");
} catch (IOException e) {
    e.printStackTrace();
}

// Method 2: Using BufferedWriter (more efficient)
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
    writer.write("Hello, World!");
    writer.newLine();
    writer.write("Line 2");
} catch (IOException e) {
    e.printStackTrace();
}

// Method 3: Using Files class
import java.nio.file.*;
try {
    String content = "Hello, World!\nLine 2";
    Files.write(Paths.get("output.txt"), content.getBytes());
} catch (IOException e) {
    e.printStackTrace();
}

Python:

# Method 1: Write mode (overwrite)
with open("output.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("Line 2\n")

# Method 2: Write multiple lines
with open("output.txt", "w") as file:
    lines = ["Hello, World!\n", "Line 2\n", "Line 3\n"]
    file.writelines(lines)

# Method 3: Using print() with file parameter
with open("output.txt", "w") as file:
    print("Hello, World!", file=file)
    print("Line 2", file=file)

3. Appending to a File

Java:

import java.io.*;

// Append mode
try (FileWriter writer = new FileWriter("output.txt", true)) {  // true = append
    writer.write("Appended line\n");
} catch (IOException e) {
    e.printStackTrace();
}

Python:

# Append mode
with open("output.txt", "a") as file:
    file.write("Appended line\n")

4. File Modes Comparison

  • Read

    • Java: FileReader, BufferedReader
    • Python: "r"
    • Description: Read existing file
  • Write

    • Java: FileWriter, BufferedWriter
    • Python: "w"
    • Description: Create/overwrite file
  • Append

    • Java: FileWriter(file, true)
    • Python: "a"
    • Description: Append to file
  • Read & Write

    • Java: RandomAccessFile
    • Python: "r+" / "w+"
    • Description: Both read and write
  • Binary Read

    • Java: FileInputStream
    • Python: "rb"
    • Description: Read binary file
  • Binary Write

    • Java: FileOutputStream
    • Python: "wb"
    • Description: Write binary file

5. Reading and Writing Different Data Types

Reading Numbers

Java:

import java.io.*;
import java.util.Scanner;

try (Scanner scanner = new Scanner(new File("numbers.txt"))) {
    while (scanner.hasNextInt()) {
        int num = scanner.nextInt();
        System.out.println(num);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

Python:

# Method 1: Read and convert
with open("numbers.txt", "r") as file:
    for line in file:
        num = int(line.strip())
        print(num)

# Method 2: List comprehension
with open("numbers.txt", "r") as file:
    numbers = [int(line.strip()) for line in file]
    print(numbers)

Writing Objects/Structured Data

Java (Serialization):

import java.io.*;

class Person implements Serializable {
    String name;
    int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

// Writing object
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.dat"))) {
    Person person = new Person("Alice", 25);
    out.writeObject(person);
} catch (IOException e) {
    e.printStackTrace();
}

// Reading object
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.dat"))) {
    Person person = (Person) in.readObject();
    System.out.println(person.name + " " + person.age);
} catch (IOException | ClassNotFoundException e) {
    e.printStackTrace();
}

Python (JSON - Preferred):

import json

# Writing JSON
data = {
    "name": "Alice",
    "age": 25,
    "city": "San Francisco"
}

with open("person.json", "w") as file:
    json.dump(data, file, indent=4)

# Reading JSON
with open("person.json", "r") as file:
    loaded_data = json.load(file)
    print(loaded_data["name"])  # Alice

Python (Pickle - Serialization):

import pickle

# Writing object
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Alice", 25)

with open("person.pkl", "wb") as file:
    pickle.dump(person, file)

# Reading object
with open("person.pkl", "rb") as file:
    loaded_person = pickle.load(file)
    print(f"{loaded_person.name} {loaded_person.age}")

6. Reading CSV Files

Java:

import java.io.*;
import java.util.*;

try (BufferedReader reader = new BufferedReader(new FileReader("data.csv"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        String[] values = line.split(",");
        System.out.println("Name: " + values[0] + ", Age: " + values[1]);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Python (Simple):

with open("data.csv", "r") as file:
    for line in file:
        name, age = line.strip().split(",")
        print(f"Name: {name}, Age: {age}")

Python (Using CSV Module - Recommended):

import csv

# Reading CSV
with open("data.csv", "r") as file:
    reader = csv.DictReader(file)  # Treats first row as headers
    for row in reader:
        print(f"Name: {row['name']}, Age: {row['age']}")

# Writing CSV
import csv

data = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30},
    {"name": "Charlie", "age": 35}
]

with open("output.csv", "w", newline="") as file:
    writer = csv.DictWriter(file, fieldnames=["name", "age"])
    writer.writeheader()
    writer.writerows(data)

7. Working with File Paths

Java:

import java.io.*;
import java.nio.file.*;

// Using File class
File file = new File("data.txt");
System.out.println(file.getAbsolutePath());
System.out.println(file.exists());
System.out.println(file.isDirectory());

// Using Paths (Java 7+, preferred)
Path path = Paths.get("data.txt");
System.out.println(path.toAbsolutePath());
System.out.println(Files.exists(path));
System.out.println(Files.isDirectory(path));

// Combining paths
Path dir = Paths.get(".", "data");
Path file = dir.resolve("file.txt");

Python:

import os
from pathlib import Path

# Using os module (older style)
print(os.path.abspath("data.txt"))
print(os.path.exists("data.txt"))
print(os.path.isdir("data.txt"))

# Using pathlib (Python 3.4+, recommended)
path = Path("data.txt")
print(path.absolute())
print(path.exists())
print(path.is_dir())

# Combining paths
dir_path = Path(".") / "data"
file_path = dir_path / "file.txt"
print(file_path)

8. Creating and Deleting Files/Directories

Java:

import java.io.*;
import java.nio.file.*;

// Create file
try {
    new File("newfile.txt").createNewFile();
    // Or using Files
    Files.createFile(Paths.get("newfile.txt"));
} catch (IOException e) {
    e.printStackTrace();
}

// Create directory
new File("mydir").mkdir();
// Or create parent directories
new File("path/to/mydir").mkdirs();

// Delete file
new File("file.txt").delete();
// Or using Files
Files.delete(Paths.get("file.txt"));

// Delete directory (must be empty)
Files.deleteIfExists(Paths.get("mydir"));

Python:

import os
from pathlib import Path

# Create file (empty)
Path("newfile.txt").touch()

# Create directory
os.makedirs("mydir", exist_ok=True)
# Or using pathlib
Path("path/to/mydir").mkdir(parents=True, exist_ok=True)

# Delete file
os.remove("file.txt")
# Or using pathlib
Path("file.txt").unlink()

# Delete directory (must be empty)
os.rmdir("mydir")

9. Listing Directory Contents

Java:

import java.io.*;
import java.nio.file.*;

// Using File class
File dir = new File(".");
File[] files = dir.listFiles();
for (File file : files) {
    System.out.println(file.getName() + " - " + file.getAbsolutePath());
}

// Using Files class
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("."))) {
    for (Path path : stream) {
        System.out.println(path.getFileName());
    }
} catch (IOException e) {
    e.printStackTrace();
}

Python:

import os
from pathlib import Path

# Using os module
for filename in os.listdir("."):
    filepath = os.path.join(".", filename)
    print(f"{filename} - {os.path.abspath(filepath)}")

# Using pathlib (recommended)
for path in Path(".").iterdir():
    print(f"{path.name} - {path.absolute()}")

# Recursive listing with glob
for path in Path(".").rglob("*.txt"):  # Find all .txt files recursively
    print(path)

10. Practical Example: Log File Processing

Java:

import java.io.*;
import java.nio.file.*;

public class LogProcessor {
    public void processLogFile(String inputFile, String outputFile) {
        try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
             BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
            
            String line;
            int errorCount = 0;
            
            while ((line = reader.readLine()) != null) {
                if (line.contains("ERROR")) {
                    writer.write(line);
                    writer.newLine();
                    errorCount++;
                }
            }
            
            System.out.println("Processed " + errorCount + " error lines");
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// Usage
LogProcessor processor = new LogProcessor();
processor.processLogFile("app.log", "errors.log");

Python:

def process_log_file(input_file, output_file):
    try:
        with open(input_file, "r") as infile, open(output_file, "w") as outfile:
            error_count = 0
            
            for line in infile:
                if "ERROR" in line:
                    outfile.write(line)
                    error_count += 1
            
            print(f"Processed {error_count} error lines")
    
    except FileNotFoundError:
        print(f"File not found: {input_file}")
    except IOError as e:
        print(f"IO Error: {e}")

# Usage
process_log_file("app.log", "errors.log")

11. Reading Binary Files

Java:

import java.io.*;

try (FileInputStream fis = new FileInputStream("image.jpg");
     DataInputStream dis = new DataInputStream(fis)) {
    
    byte[] buffer = new byte[1024];
    int bytesRead;
    
    while ((bytesRead = fis.read(buffer)) != -1) {
        // Process binary data
        System.out.println("Read " + bytesRead + " bytes");
    }
    
} catch (IOException e) {
    e.printStackTrace();
}

Python:

# Reading binary file
with open("image.jpg", "rb") as file:
    buffer = file.read(1024)  # Read 1024 bytes
    while buffer:
        print(f"Read {len(buffer)} bytes")
        buffer = file.read(1024)

# Writing binary file
with open("output.jpg", "wb") as file:
    file.write(binary_data)

12. Summary Table

  • Read entire file

    • Java: Files.readAllBytes() or BufferedReader
    • Python: file.read() or with open()
  • Read line by line

    • Java: BufferedReader.readLine()
    • Python: for line in file:
  • Write to file

    • Java: FileWriter / BufferedWriter
    • Python: file.write() or with open()
  • Append to file

    • Java: FileWriter(file, true)
    • Python: open(file, "a")
  • File operations

    • Java: File class or Files class
    • Python: os module or pathlib
  • Path handling

    • Java: File / Paths / Path
    • Python: os.path / pathlib.Path
  • CSV handling

    • Java: Manual parsing or 3rd party
    • Python: csv module (built-in)
  • JSON handling

    • Java: org.json or Gson
    • Python: json module (built-in)
  • Object serialization

    • Java: ObjectOutputStream
    • Python: pickle module
  • Check file exists

    • Java: file.exists() or Files.exists()
    • Python: path.exists() or os.path.exists()
  • Delete file

    • Java: file.delete() or Files.delete()
    • Python: os.remove() or path.unlink()
  • List directory

    • Java: file.listFiles() / DirectoryStream
    • Python: os.listdir() / Path.iterdir()