Day 28: File Handling

Objective

Learn how to work with files by creating a program that reads and writes text files. This task will help you understand how to save data for later use and read external data into your program.

For example:

Task: Read a list of names from a file, process them, and save a new file with the results.

Input File: names.txt containing:

Alice
Bob
Charlie

Output File: greetings.txt containing:

Hello, Alice!
Hello, Bob!
Hello, Charlie!

Why This Challenge Is Important

File handling is essential for many real-world applications. You’ll learn:

  • Reading data from files for input.
  • Writing data to files for output.
  • Proper file management techniques like closing files and handling errors.

Steps to Solve

1. Understand the Problem

The program should:

  1. Read a file (e.g., names.txt) line by line.
  2. Process each line (e.g., add a greeting).
  3. Write the results to a new file (e.g., greetings.txt).

2. Plan Your Solution

  1. Open a file in read mode to retrieve data.
  2. Loop through the lines and process each one.
  3. Open another file in write mode and save the processed data.
  4. Ensure proper file closure or use a context manager to manage resources safely.

Code Examples

Python Example

def process_file():
    try:
        # Step 1: Read the file
        with open("names.txt", "r") as input_file:
            names = input_file.readlines()

        # Step 2: Process the names
        greetings = [f"Hello, {name.strip()}!\n" for name in names]

        # Step 3: Write the processed data to a new file
        with open("greetings.txt", "w") as output_file:
            output_file.writelines(greetings)

        print("Processing complete! Check 'greetings.txt' for the results.")

    except FileNotFoundError:
        print("Error: The file 'names.txt' was not found.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

process_file()

Java Example

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileHandlingExample {
    public static void main(String[] args) {
        try {
            // Step 1: Read the file
            BufferedReader reader = new BufferedReader(new FileReader("names.txt"));
            List<String> names = new ArrayList<>();
            String line;

            while ((line = reader.readLine()) != null) {
                names.add(line.trim());
            }
            reader.close();

            // Step 2: Process the names
            List<String> greetings = new ArrayList<>();
            for (String name : names) {
                greetings.add("Hello, " + name + "!\n");
            }

            // Step 3: Write the processed data to a new file
            BufferedWriter writer = new BufferedWriter(new FileWriter("greetings.txt"));
            for (String greeting : greetings) {
                writer.write(greeting);
            }
            writer.close();

            System.out.println("Processing complete! Check 'greetings.txt' for the results.");

        } catch (FileNotFoundException e) {
            System.out.println("Error: The file 'names.txt' was not found.");
        } catch (IOException e) {
            System.out.println("An unexpected error occurred: " + e.getMessage());
        }
    }
}

JavaScript Example

const fs = require("fs");

function processFile() {
    try {
        // Step 1: Read the file
        const data = fs.readFileSync("names.txt", "utf8");
        const names = data.split("\n").map(name => name.trim());

        // Step 2: Process the names
        const greetings = names.map(name => `Hello, ${name}!\n`);

        // Step 3: Write the processed data to a new file
        fs.writeFileSync("greetings.txt", greetings.join(""));
        console.log("Processing complete! Check 'greetings.txt' for the results.");

    } catch (err) {
        if (err.code === "ENOENT") {
            console.error("Error: The file 'names.txt' was not found.");
        } else {
            console.error("An unexpected error occurred:", err.message);
        }
    }
}

processFile();

Edge Cases to Consider

  1. Empty Input File: Handle cases where the file has no data.
    • Output: An empty output file or a warning message.
  2. File Not Found: Display a clear error if the file doesn’t exist.
  3. Special Characters: Ensure special characters in the input file are handled correctly.

Extensions to Explore

  1. Append Mode: Modify the program to add new data to an existing file instead of overwriting it.
  2. CSV Files: Extend the program to process CSV files (e.g., reading names and corresponding email addresses).
  3. Error Logging: Save error messages to a log file for debugging purposes.

What You’ve Learned

  • The basics of file input/output operations.
  • Using loops and string manipulation to process file content.
  • Error handling and resource management while working with files.

Next Steps

In Day 29: Mini To-Do List, you create a mini to-do list application that allows the user to:

  • Save tasks to a file so they persist between sessions.
  • Add tasks.
  • View the list of tasks.
  • Mark tasks as completed.