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!
File handling is essential for many real-world applications. You’ll learn:
The program should:
names.txt
) line by line.greetings.txt
).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()
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());
}
}
}
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();
In Day 29: Mini To-Do List, you create a mini to-do list application that allows the user to: