Python · Advanced Python

File Handling — Practice Questions

50 questions. Try each one yourself before checking the answer.

Q1open() / write() / close()Easy

Open "notes.txt" in write mode, write the line "Hello, File!", and close it manually (no with yet).

Q2read()Easy

Open "notes.txt" (from Q1) in read mode, print its entire contents using .read(), then close it.

Q3withEasy

Rewrite Q1 using a with statement instead of manual open()/close().

Q4withEasy

Rewrite Q2 using a with statement, and explain in a comment why the file doesn't need an explicit .close().

Q5write() Multiple LinesEasy

Write three separate lines to "notes.txt", each ending with "\n", using multiple .write() calls.

Q6readline()Easy

Using "notes.txt" from Q5, read just the FIRST line using .readline() and print it.

Q7readlines()Easy

Using "notes.txt" from Q5, read ALL lines into a list using .readlines() and print the list.

Q8Append ModeEasy

Append a new line, "Line 4\n", to "notes.txt" without erasing what's already there.

Q9Iterating a FileEasy

Open "notes.txt" and print each line by iterating directly over the file object (no .readlines()).

Q10Overwrite vs AppendEasy

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.

Q11write() with LoopMedium

Given fruits = ["apple", "banana", "cherry"], write each fruit on its own line to "fruits.txt" using a for loop.

Q12writelines()Medium

Given lines = ["First\n", "Second\n", "Third\n"], write all of them in one call using .writelines().

Q13strip() with FilesMedium

Read "fruits.txt" (from Q11) line by line, stripping the trailing newline from each before printing.

Q14Counting LinesMedium

Count and print the number of lines in "fruits.txt".

Q15Counting WordsMedium

Write a paragraph to a file, then read it back and count the total number of words using .split().

Q16Reading User Input to FileMedium

Ask the user for 3 lines of text and write each to "input_log.txt", one per line.

Q17Copying File ContentMedium

Copy the contents of "fruits.txt" into a new file "fruits_copy.txt".

Q18Character CountingMedium

Read "fruits.txt" and print the total number of characters in it (using len()).

Q19File ModesMedium

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.

Q20Building Lines from a ListMedium

Given students = [("Alice", 88), ("Bob", 95)], write a formatted line per student ("Alice: 88") to "grades.txt".

Q21Real-WorldMedium

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

Q22Real-WorldMedium

Read "grades.txt" (from Q20) and print only the lines belonging to students who scored above 90.

Q23Word FrequencyMedium

Write a short paragraph to a file, read it back, and build a word-frequency dictionary from its contents.

Q24Real-WorldMedium

Given a list of usernames, write them to "users.txt", then read the file back and print whether a specific username exists in it.

Q25Real-WorldMedium

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.

Q26Filtering File ContentMedium

Given "grades.txt" (from Q20), write a NEW file "passed.txt" containing only students who scored 40 or above.

Q27Real-WorldMedium

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.

Q28DebuggingMedium

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

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

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.

Q31seek() / tell()Hard

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.

Q32truncate()Hard

Write a long line to a file, then reopen it and use .truncate() to cut it down to the first 10 characters.

Q33CSV WritingHard

Using the csv module, write a list of (name, score) rows to "scores.csv", including a header row.

Q34CSV ReadingHard

Using the csv module, read "scores.csv" (from Q33) and print each row, skipping the header.

Q35CSV DictReaderHard

Using csv.DictReader, read "scores.csv" and print each student's name and score as a labeled sentence.

Q36JSON WritingHard

Using the json module, save profile = {"name": "Asha", "age": 22, "skills": ["Python", "SQL"]} to "profile.json".

Q37JSON ReadingHard

Using the json module, read "profile.json" (from Q36) back into a Python dictionary and print the "skills" list.

Q38JSON FormattingHard

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.

Q39CSV + DictHard

Read "scores.csv" using csv.DictReader and build a plain Python dictionary mapping name to score (as an int).

Q40DebuggingHard

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)
Q41Mini-ProjectMini-Project

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.

Q42Mini-ProjectMini-Project

Build a "Simple Diary App". Ask the user for a diary entry title and body, and append a formatted entry to "diary.txt".

Q43Mini-ProjectMini-Project

Build a "Student Grade CSV Manager": write a starting roster to "roster.csv", then read it back and print the class average.

Q44Mini-ProjectMini-Project

Build a "JSON Settings Manager". Save a settings dict to "settings.json", then load it back, update one value, and save it again.

Q45Mini-ProjectMini-Project

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.

Q46InterviewInterview

Explain why with open(...) as file: is preferred over manual open()/close(), demonstrating the resource-leak risk of forgetting .close() after an error.

Q47InterviewInterview

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."

Q48InterviewInterview

Explain when to choose CSV versus JSON for storing structured data, demonstrating the same data saved both ways.

Q49InterviewInterview

Explain the difference between text mode ("r") and binary mode ("rb") when opening a file, and demonstrate reading the same text file both ways.

Q50CapstoneInterview

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