Python · Advanced Python

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.

Q1WritingEasyMust Do

Create a file called notes.txt containing the single line Hello, file!, then confirm it exists by reading it back.

Q2ReadingEasyMust Do

Write three lines to a file, then read the whole thing back with .read() and print it.

Q3ModesEasy

Show that "r" is the default mode by opening a file for reading without naming a mode at all.

Q4withEasyMust Do

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.

Q5withEasy

Prove that with really does close the file, by checking the file object's .closed attribute inside and after the block.

Q6WritingEasy

Write the numbers 1 to 5 to a file, one per line, using a loop.

Q7readline()Easy

Read a file one line at a time with .readline(), printing the first two lines only.

Q8readlines()Easy

Read a file into a list of lines with .readlines(), then print the list and its length.

Q9IteratingEasyMust Do

Loop over a file object directly to print each line, and note in a comment why this is the preferred way.

Q10IteratingEasy

Print each line of a file with its line number, starting at 1.

Q11ModesEasyMust Do

Use append mode "a" to add a line to an existing file without destroying what is already there.

Q12ModesEasyMust Do

Demonstrate that "w" destroys whatever the file held before, by writing, overwriting, and reading.

Q13ModesEasy

Use "x" mode to create a file only if it does not already exist, and explain what happens on a second attempt.

Q14CountingEasy

Count how many lines a file has, without loading it all into memory.

Q15CountingEasy

Count the lines, words and characters in a file, and print all three.

Q16StrippingEasyMust Do

Read a file into a list of lines with the trailing newlines removed.

Q17writelines()Easy

Write a list of strings to a file using .writelines(), and explain the trap in a comment.

Q18WritingEasy

Write a list of names to a file with a loop, adding the newline yourself, then read it back as a list.

Q19read(n)Easy

Read only the first 10 characters of a file, then the next 10.

Q20tell()Easy

Use .tell() to show where in the file you currently are, before and after reading.

Q21seek()EasyMust Do

Read a file, then rewind with .seek(0) and read it again, showing that without the rewind the second read is empty.

Q22seek()Easy

Use .seek() to jump to a specific position and read from there.

Q23truncate()Easy

Use .truncate() to cut a file down to its first 10 characters.

Q24ModesEasy

Use "r+" to read a file and then write to it in the same session.

Q25WritingEasy

Write a small formatted report to a file — a header, three aligned rows and a total — then print the file.

Q26CopyingMedium

Copy the contents of one file into another, then confirm both hold the same text.

Q27AppendingMedium

Build a log file where each new entry is numbered, by counting the existing lines before appending.

Q28ReadingMediumMust Do

Write numbers to a file, then read them back and print the count, total, average, highest and lowest.

Q29SearchingMedium

Search a file for a word and report whether it was found, and on which line.

Q30CountingMedium

Count how many times a word appears in a file, ignoring case.

Q31SearchingMedium

Print every line containing a search term, with its line number, and report how many matched.

Q32ModifyingMediumMust Do

Replace every occurrence of a word throughout a file, using the read-modify-write pattern.

Q33ModifyingMedium

Remove all blank lines from a file and report how many were removed.

Q34ModifyingMedium

Reverse the order of the lines in a file.

Q35SortingMedium

Sort the lines of a file alphabetically and write them to a new file.

Q36Sets & FilesMediumMust Do

Remove duplicate lines from a file, keeping the first occurrence of each in its original order.

Q37CopyingMedium

Merge two files into a third, with a header naming each source.

Q38ReadingMedium

Find and print the longest line in a file, with its length and line number.

Q39Dictionaries & FilesMedium

Count how often each word appears in a file and print the five most common.

Q40Dictionaries & FilesMedium

Save a dictionary to a file as key=value lines.

Q41Dictionaries & FilesMedium

Read those key=value lines back into a dictionary, ignoring blank lines and # comments.

Q42CSVMediumMust Do

Use the csv module to write a table of student records to a CSV file, including a header row.

Q43CSVMedium

Read that CSV back with csv.reader, printing the header separately from the data rows.

Q44CSVMedium

Read a CSV and total a numeric column, converting the text to numbers as you go.

Q45CSVMedium

Use csv.DictWriter to write records from a list of dictionaries.

Q46CSVMediumMust Do

Use csv.DictReader to read a CSV as dictionaries, accessing fields by name instead of position.

Q47JSONMedium

Save a dictionary to a file as JSON with json.dump(), then print the raw file.

Q48JSONMediumMust Do

Load that JSON file back with json.load() and prove the types survived the round trip.

Q49JSONMedium

Save a nested structure — a list of dictionaries, each holding a list — as JSON with indent=2, and read it back.

Q50JSONMedium

Show the difference between json.dump/load (files) and json.dumps/loads (strings).

Q51Real-WorldMediumMust Do

Read student marks from a text file of name,mark lines and print a class report with the average and the top student.

Q52Real-WorldMedium

Analyse a log file: count how many entries of each level there are and print the breakdown with percentages.

Q53CSVMediumMust Do

Read an inventory CSV and report the total stock value, plus any item below a reorder level.

Q54CSVMedium

Save a contact book to CSV and reload it into a dictionary keyed by name.

Q55Real-WorldMediumMust Do

Load a config file over a set of defaults, so any missing option falls back sensibly, and report which values came from the file.

Q56Real-WorldMedium

Write a wc-style tool that reports lines, words, characters and the average words per line for a file.

Q57CSVMedium

Read a marks CSV, compute each student's average and grade, and write the results to a new CSV.

Q58CSVMedium

Filter a CSV, writing only the rows that meet a condition to a new file, and report how many were kept.

Q59JSONMediumMust Do

Build an expense tracker that saves to JSON and reloads, so totals survive between runs.

Q60JSONMedium

Store nested settings as JSON and read a deeply nested value back safely with .get().

Q61CSVMedium

Add a calculated column to an existing CSV and write the result to a new file.

Q62CSVMedium

Sort a CSV by a numeric column, highest first, and write the sorted file.

Q63ConvertingMedium

Convert a CSV file into JSON, turning each row into a dictionary in a list.

Q64ConvertingMedium

Convert a JSON list of records back into a CSV file.

Q65Sets & FilesMediumMust Do

Compare two files and report which lines were added, removed and unchanged.

Q66Dictionaries & FilesMedium

Build an index mapping each word in a file to the line numbers it appears on.

Q67Real-WorldMedium

Read a file of numbers, write out only the valid ones, and report each line that could not be understood — without using try.

Q68Real-WorldMedium

Split one large file into several smaller ones of a fixed number of lines each.

Q69Real-WorldMedium

Write a file backup routine that copies a file to a numbered backup name before overwriting it.

Q70JSONMedium

Keep a running high-score table in a JSON file that survives repeated updates.

Q71DebuggingHardMust Do

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")
Q72withHard

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.

Q73seek()Hard

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}'")
Q74WritingHard

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())
Q75readlines()HardMust Do

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)
Q76MemoryHard

Compare reading a whole file into memory with reading it line by line, and explain when each is the wrong choice.

Q77Binary ModeHard

Write and read a file in binary mode, and show how it differs from text mode.

Q78WritingHard

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)
Q79ModifyingHard

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()))
Q80ModesHard

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())
Q81CSVHardMust Do

Show why splitting a CSV line on commas breaks, and why the csv module does not.

Q82CSVHard

Show what happens when newline="" is left out of a CSV write, and explain why it matters.

Q83JSONHard

Show which Python types survive a JSON round trip unchanged and which do not.

Q84JSONHard

Show that JSON turns every dictionary key into a string, and give a way to restore numeric keys.

Q85ModesHard

Show what happens when you try to write to a file opened for reading, and vice versa.

Q86Mini-ProjectMini-Project

Build a To-Do List that saves to a text file, so tasks survive between runs. Offer add, list, complete and quit.

Q87Mini-ProjectMini-ProjectMust Do

Build a Student Record Manager backed by CSV. Offer add, list sorted by mark, class statistics and quit — reloading from the file each time.

Q88Mini-ProjectMini-Project

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.

Q89Mini-ProjectMini-ProjectMust Do

Build a Contact Book stored as JSON, with add, search, delete, list and a city breakdown — saving after every change.

Q90Mini-ProjectMini-Project

Build an Inventory Manager on CSV: add stock, sell, a value report and a low-stock reorder list, saving after each change.

Q91Mini-ProjectMini-Project

Build a Quiz that loads its questions from a file, runs the quiz, and appends each attempt's score to a results file.

Q92Mini-ProjectMini-Project

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.

Q93Mini-ProjectMini-Project

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.

Q94Mini-ProjectMini-Project

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.

Q95Mini-ProjectMini-Project

Build a File Merge and Deduplicate tool: combine several files, remove duplicate lines, sort the result, and write a report of what happened.

Q96InterviewInterview

Explain what with actually does and why it is not merely a shortcut for .close(). Demonstrate the difference.

Q97ModesInterview

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.

Q98ReadingInterview

Compare the four ways of reading a file — .read(), .read(n), .readlines() and iterating — on memory use and on what each is for.

Q99CSVInterview

Compare plain text, CSV and JSON as storage formats. Say what each preserves, what it loses, and when you would pick it.

Q100CapstoneInterviewMust Do

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