File Handling — Practice Questions
50 questions. Try each one yourself before checking the answer.
Open "notes.txt" in write mode, write the line "Hello, File!", and close it manually (no with yet).
Open "notes.txt" (from Q1) in read mode, print its entire contents using .read(), then close it.
Rewrite Q1 using a with statement instead of manual open()/close().
Rewrite Q2 using a with statement, and explain in a comment why the file doesn't need an explicit .close().
Write three separate lines to "notes.txt", each ending with "\n", using multiple .write() calls.
Using "notes.txt" from Q5, read just the FIRST line using .readline() and print it.
Using "notes.txt" from Q5, read ALL lines into a list using .readlines() and print the list.
Append a new line, "Line 4\n", to "notes.txt" without erasing what's already there.
Open "notes.txt" and print each line by iterating directly over the file object (no .readlines()).
Demonstrate the difference between "w" mode (overwrites) and "a" mode (appends) by writing to "notes.txt" twice with each mode and printing the final content.
Given fruits = ["apple", "banana", "cherry"], write each fruit on its own line to "fruits.txt" using a for loop.
Given lines = ["First\n", "Second\n", "Third\n"], write all of them in one call using .writelines().
Read "fruits.txt" (from Q11) line by line, stripping the trailing newline from each before printing.
Count and print the number of lines in "fruits.txt".
Write a paragraph to a file, then read it back and count the total number of words using .split().
Ask the user for 3 lines of text and write each to "input_log.txt", one per line.
Copy the contents of "fruits.txt" into a new file "fruits_copy.txt".
Read "fruits.txt" and print the total number of characters in it (using len()).
Demonstrate "x" (exclusive create) mode by creating a brand-new file. Explain in a comment what happens if you try "x" on a file that already exists.
Given students = [("Alice", 88), ("Bob", 95)], write a formatted line per student ("Alice: 88") to "grades.txt".
Build a simple "Notes App": ask the user for a note and append it to "my_notes.txt" each time this runs (never overwriting old notes).
Read "grades.txt" (from Q20) and print only the lines belonging to students who scored above 90.
Write a short paragraph to a file, read it back, and build a word-frequency dictionary from its contents.
Given a list of usernames, write them to "users.txt", then read the file back and print whether a specific username exists in it.
Build a "line counter" tool: write a multi-line poem to a file, then read it back and print how many lines, words, and characters it contains.
Given "grades.txt" (from Q20), write a NEW file "passed.txt" containing only students who scored 40 or above.
Ask the user for their name and age, and save it as a formatted profile line to "profiles.txt", appending so multiple runs build up a list of profiles.
The following code is meant to add a line to an existing file but instead erases everything else in it. Find and fix the bug.
with open("notes.txt", "w") as file:
file.write("New line\n")The following code prints every line with an extra blank line between them. Find and fix the bug.
with open("fruits.txt", "r") as file:
for line in file:
print(line)Write a formatted report of products = {"Pen": 10.5, "Notebook": 45.0} to "report.txt", with aligned columns, then read and print the file's contents.
Open "notes.txt", read the first 5 characters, print the current position with .tell(), then use .seek(0) to jump back to the start and read again.
Write a long line to a file, then reopen it and use .truncate() to cut it down to the first 10 characters.
Using the csv module, write a list of (name, score) rows to "scores.csv", including a header row.
Using the csv module, read "scores.csv" (from Q33) and print each row, skipping the header.
Using csv.DictReader, read "scores.csv" and print each student's name and score as a labeled sentence.
Using the json module, save profile = {"name": "Asha", "age": 22, "skills": ["Python", "SQL"]} to "profile.json".
Using the json module, read "profile.json" (from Q36) back into a Python dictionary and print the "skills" list.
Save the same profile dictionary from Q36 to "profile_pretty.json", but formatted with indentation using json.dump(..., indent=4) so it's human-readable.
Read "scores.csv" using csv.DictReader and build a plain Python dictionary mapping name to score (as an int).
The following JSON-writing code crashes with a TypeError. Find and fix the bug.
import json
data = {"name": "Bob", "joined": {1, 2, 3}}
with open("data.json", "w") as file:
json.dump(data, file)Build a "Persistent To-Do List". Load existing tasks from "todo.txt" at startup (if the file has content), let the user add one new task, then save the full updated list back.
Build a "Simple Diary App". Ask the user for a diary entry title and body, and append a formatted entry to "diary.txt".
Build a "Student Grade CSV Manager": write a starting roster to "roster.csv", then read it back and print the class average.
Build a "JSON Settings Manager". Save a settings dict to "settings.json", then load it back, update one value, and save it again.
Build a "Log Analyzer". Write a small log file containing lines tagged INFO, WARNING, and ERROR, then read it back and print how many of each tag appear.
Explain why with open(...) as file: is preferred over manual open()/close(), demonstrating the resource-leak risk of forgetting .close() after an error.
Explain the memory tradeoff between .read() (loads the whole file at once) and iterating line-by-line, and demonstrate the line-by-line approach on a file, framed as "what you'd do for a multi-gigabyte log file."
Explain when to choose CSV versus JSON for storing structured data, demonstrating the same data saved both ways.
Explain the difference between text mode ("r") and binary mode ("rb") when opening a file, and demonstrate reading the same text file both ways.
Build a "File Handling Toolkit Report" — the most complete demonstration in this module. Write student records to a .txt file, a .csv file, and a .json file from the same data, then read all three back and print a confirmation that each round-trips correctly.
Still stuck on something?
Book a free 1-on-1 session and we'll work through it together.
Book a Free Session