File Handling: Practice Questions
100 questions. Try each one yourself before checking the answer.
Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.
Create a file called notes.txt containing the single line Hello, file!, then confirm it exists by reading it back.
Write three lines to a file, then read the whole thing back with .read() and print it.
Show that "r" is the default mode by opening a file for reading without naming a mode at all.
Open a file the old way — with open() and .close() — then show the same thing with with, and explain in a comment why with is safer.
Prove that with really does close the file, by checking the file object's .closed attribute inside and after the block.
Write the numbers 1 to 5 to a file, one per line, using a loop.
Read a file one line at a time with .readline(), printing the first two lines only.
Read a file into a list of lines with .readlines(), then print the list and its length.
Loop over a file object directly to print each line, and note in a comment why this is the preferred way.
Print each line of a file with its line number, starting at 1.
Use append mode "a" to add a line to an existing file without destroying what is already there.
Demonstrate that "w" destroys whatever the file held before, by writing, overwriting, and reading.
Use "x" mode to create a file only if it does not already exist, and explain what happens on a second attempt.
Count how many lines a file has, without loading it all into memory.
Count the lines, words and characters in a file, and print all three.
Read a file into a list of lines with the trailing newlines removed.
Write a list of strings to a file using .writelines(), and explain the trap in a comment.
Write a list of names to a file with a loop, adding the newline yourself, then read it back as a list.
Read only the first 10 characters of a file, then the next 10.
Use .tell() to show where in the file you currently are, before and after reading.
Read a file, then rewind with .seek(0) and read it again, showing that without the rewind the second read is empty.
Use .seek() to jump to a specific position and read from there.
Use .truncate() to cut a file down to its first 10 characters.
Use "r+" to read a file and then write to it in the same session.
Write a small formatted report to a file — a header, three aligned rows and a total — then print the file.
Copy the contents of one file into another, then confirm both hold the same text.
Build a log file where each new entry is numbered, by counting the existing lines before appending.
Write numbers to a file, then read them back and print the count, total, average, highest and lowest.
Search a file for a word and report whether it was found, and on which line.
Count how many times a word appears in a file, ignoring case.
Print every line containing a search term, with its line number, and report how many matched.
Replace every occurrence of a word throughout a file, using the read-modify-write pattern.
Remove all blank lines from a file and report how many were removed.
Reverse the order of the lines in a file.
Sort the lines of a file alphabetically and write them to a new file.
Remove duplicate lines from a file, keeping the first occurrence of each in its original order.
Merge two files into a third, with a header naming each source.
Find and print the longest line in a file, with its length and line number.
Count how often each word appears in a file and print the five most common.
Save a dictionary to a file as key=value lines.
Read those key=value lines back into a dictionary, ignoring blank lines and # comments.
Use the csv module to write a table of student records to a CSV file, including a header row.
Read that CSV back with csv.reader, printing the header separately from the data rows.
Read a CSV and total a numeric column, converting the text to numbers as you go.
Use csv.DictWriter to write records from a list of dictionaries.
Use csv.DictReader to read a CSV as dictionaries, accessing fields by name instead of position.
Save a dictionary to a file as JSON with json.dump(), then print the raw file.
Load that JSON file back with json.load() and prove the types survived the round trip.
Save a nested structure — a list of dictionaries, each holding a list — as JSON with indent=2, and read it back.
Show the difference between json.dump/load (files) and json.dumps/loads (strings).
Read student marks from a text file of name,mark lines and print a class report with the average and the top student.
Analyse a log file: count how many entries of each level there are and print the breakdown with percentages.
Read an inventory CSV and report the total stock value, plus any item below a reorder level.
Save a contact book to CSV and reload it into a dictionary keyed by name.
Load a config file over a set of defaults, so any missing option falls back sensibly, and report which values came from the file.
Write a wc-style tool that reports lines, words, characters and the average words per line for a file.
Read a marks CSV, compute each student's average and grade, and write the results to a new CSV.
Filter a CSV, writing only the rows that meet a condition to a new file, and report how many were kept.
Build an expense tracker that saves to JSON and reloads, so totals survive between runs.
Store nested settings as JSON and read a deeply nested value back safely with .get().
Add a calculated column to an existing CSV and write the result to a new file.
Sort a CSV by a numeric column, highest first, and write the sorted file.
Convert a CSV file into JSON, turning each row into a dictionary in a list.
Convert a JSON list of records back into a CSV file.
Compare two files and report which lines were added, removed and unchanged.
Build an index mapping each word in a file to the line numbers it appears on.
Read a file of numbers, write out only the valid ones, and report each line that could not be understood — without using try.
Split one large file into several smaller ones of a fixed number of lines each.
Write a file backup routine that copies a file to a numbered backup name before overwriting it.
Keep a running high-score table in a JSON file that survives repeated updates.
This is meant to add a line to a file but wipes it out instead. Explain exactly when the damage happens and fix it two ways.
with open("important.txt", "w") as f:
f.write("line one\nline two\n")
with open("important.txt", "w") as f:
f.write("line three\n")Show that data written to a file may not actually be on disk until the file is closed, and explain why with prevents the problem.
This counts the lines correctly but then reports the file as empty. Find the bug.
with open("data.txt", "w") as f:
f.write("alpha\nbravo\ncharlie\n")
with open("data.txt") as f:
count = 0
for line in f:
count += 1
contents = f.read()
print(f"{count} lines")
print(f"contents: '{contents}'")This should write three separate lines but produces one. Explain and fix.
names = ["Asha", "Raj", "Meera"]
with open("names.txt", "w") as f:
f.writelines(names)
with open("names.txt") as f:
print(f.read())This search never finds the name, even though it is clearly in the file. Find the bug.
with open("names.txt", "w") as f:
f.write("Asha\nRaj\nMeera\n")
with open("names.txt") as f:
names = f.readlines()
if "Raj" in names:
print("found Raj")
else:
print("Raj is not in the list")
print(names)Compare reading a whole file into memory with reading it line by line, and explain when each is the wrong choice.
Write and read a file in binary mode, and show how it differs from text mode.
This crashes with a TypeError. Explain why files are stricter than print() and give two fixes.
count = 42
with open("count.txt", "w") as f:
f.write(count)This read-modify-write leaves rubbish at the end of the file when the new text is shorter. Explain and fix.
with open("data.txt", "w") as f:
f.write("a very long original line of text\n")
with open("data.txt", "r+") as f:
contents = f.read()
f.seek(0)
f.write("short\n")
with open("data.txt") as f:
print(repr(f.read()))A log keeps only ever showing one entry. Find the bug and explain the difference between the two modes involved.
def log(message):
with open("app.log", "w") as f:
f.write(f"{message}\n")
log("started")
log("processing")
log("finished")
with open("app.log") as f:
print(f.read())Show why splitting a CSV line on commas breaks, and why the csv module does not.
Show what happens when newline="" is left out of a CSV write, and explain why it matters.
Show which Python types survive a JSON round trip unchanged and which do not.
Show that JSON turns every dictionary key into a string, and give a way to restore numeric keys.
Show what happens when you try to write to a file opened for reading, and vice versa.
Build a To-Do List that saves to a text file, so tasks survive between runs. Offer add, list, complete and quit.
Build a Student Record Manager backed by CSV. Offer add, list sorted by mark, class statistics and quit — reloading from the file each time.
Build a Log Analyser that reads a log file and reports entries per level, the busiest source, all error messages, and writes a summary file.
Build a Contact Book stored as JSON, with add, search, delete, list and a city breakdown — saving after every change.
Build an Inventory Manager on CSV: add stock, sell, a value report and a low-stock reorder list, saving after each change.
Build a Quiz that loads its questions from a file, runs the quiz, and appends each attempt's score to a results file.
Build a Text File Statistics report that reads a file and writes a full analysis to a second file: counts, averages, the longest line, top words and letter frequency.
Build a Sales Report Generator: read a CSV of transactions, aggregate by region and product, and write both a text report and a summary CSV.
Build a Simple Database on JSON: records keyed by ID, with add, find by ID, search any field, delete and a stored auto-incrementing next ID.
Build a File Merge and Deduplicate tool: combine several files, remove duplicate lines, sort the result, and write a report of what happened.
Explain what with actually does and why it is not merely a shortcut for .close(). Demonstrate the difference.
Set out every file mode, what it does to an existing file, and what happens when the file is missing. Demonstrate the ones that differ most.
Compare the four ways of reading a file — .read(), .read(n), .readlines() and iterating — on memory use and on what each is for.
Compare plain text, CSV and JSON as storage formats. Say what each preserves, what it loses, and when you would pick it.
Capstone. Build a File Toolkit Report. Create a source text file, then in one program: copy it, count its lines, words and characters, find its longest line, deduplicate and sort it, write it out as CSV and as JSON, read both back, and print a report proving every round trip worked.
Still stuck on something?
Book a free 1-on-1 session and we'll work through it together.
Book a Free Session