Python file handling MCQ questions with answers
Open modes, reading, writing and the with statement: the file questions CBSE asks.
0 of 20 answered
Question 1 · Easy
What is the output of this code?
with open("notes.txt", "w") as f: f.write("Hello") f.write("World") with open("notes.txt") as f: print(f.read())
Show the answer
Answer: D
Run this code in the editorwrite()adds exactly the text it is given: no space and no newline. The two calls put HelloWorld on one line; add\nyourself where a line should end. Both calls happen in the samewithblock, so the second one does not replace the first.Question 2 · Easy
What is the output of this code?
with open("log.txt", "w") as f: f.write("one\n") with open("log.txt", "a") as f: f.write("two\n") with open("log.txt") as f: print(f.read().split())
Show the answer
Answer: B
Mode "a" opens the file for appending: new text goes after what is already there, so the file holds both lines.
Run this code in the editorsplit()with no argument splits on any whitespace, newlines included, and drops it. Mode "w" in the secondopenwould have erased "one".Question 3 · Easy
What is the output of this code?
with open("story.txt", "w") as f: f.write("the cat sat\non the mat\n") with open("story.txt") as f: words = f.read().split() print(len(words), words.count("the"))
Show the answer
Answer: A
Run this code in the editorread()returns the whole file as one string, andsplit()breaks it on spaces and newlines alike, giving six words, two of which are "the". 2 would be the number of lines, which is whatlen(f.readlines())counts.Question 4 · Medium
What is the output of this code?
with open("poem.txt", "w") as f: f.write("Roses are red\nViolets are blue\nSugar is sweet\n") with open("poem.txt") as f: line = f.readline() print(line) print(f.readline(), end="")
Show the answer
Answer: C
Run this code in the editorreadline()returns one line including its\n, andprintadds another newline, so a blank line follows the first line. The secondreadline()continues from where the first stopped, giving the second line, andend=""stopsprintadding a newline of its own.Question 5 · Medium
What is the output of this code?
with open("data.txt", "w") as f: f.write("a\nb\nc") with open("data.txt") as f: lines = f.readlines() print(lines, len(lines))
Show the answer
Answer: A
Run this code in the editorreadlines()returns a list of lines, each keeping its\n. The text written does not end with a newline, so the last item is 'c' without one.f.read().splitlines()would give the lines without their newlines.Question 6 · Medium
What is the output of this code?
with open("code.txt", "w") as f: f.write("ABCDEFGH") with open("code.txt") as f: first = f.read(3) pos = f.tell() f.seek(1) print(first, pos, f.read(2))
Show the answer
Answer: C
Run this code in the editorread(3)reads three characters and leaves the position at 3, whichtell()reports (positions count from 0).seek(1)moves back to the second character, soread(2)gives BC. Reading on without theseekwould have given DE.Question 7 · Medium
What is the output of this code?
with open("items.txt", "w") as f: f.writelines(["pen", "ink", "nib"]) with open("items.txt") as f: print(f.readlines())
Show the answer
Answer: D
Despite its name,
Run this code in the editorwritelines()does not add newlines: it writes each string as it is, one after another. The file holds peninknib on a single line, soreadlines()returns a list with one item.Question 8 · Medium
What is the output of this code?
import csv with open("marks.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerow(["name", "marks"]) writer.writerow(["Asha", 91]) with open("marks.csv", newline="") as f: for row in csv.reader(f): print(row)
Show the answer
Answer: B
Run this code in the editorcsv.writerturns each list into one comma-separated line, andcsv.readergives each line back as a list of strings. A CSV file stores only text, so the number 91 comes back as '91'; convert it withint()when you need a number.Question 9 · Hard
What is the output of this code?
with open("scores.txt", "w+") as f: f.write("90 85 77") print(repr(f.read())) f.seek(0) print(f.read().split())
Show the answer
Answer: B
Mode "w+" allows reading and writing, but after
Run this code in the editorwrite()the position is at the end of the file, so the firstread()returns an empty string.seek(0)moves back to the start and the second read gets the text;split()gives strings, not numbers.Question 10 · Hard
What is the output of this code?
with open("names.txt", "w") as f: f.write("Anna\nBob\nRiya") count = 0 with open("names.txt") as f: for line in f: if line.endswith("a"): count += 1 print(count)
Show the answer
Answer: D
Each line read in the loop keeps its newline, so the first line is "Anna\n", which ends with
Run this code in the editor\n, not "a". Only "Riya" has no newline after it, because the text written does not end with one.line.rstrip("\n").endswith("a")would count both names.Question 11 · Hard
What is the output of this code?
import json point = {"x": (3, 4)} with open("point.json", "w") as f: json.dump(point, f) with open("point.json") as f: loaded = json.load(f) print(loaded, loaded == point)
Show the answer
Answer: C
JSON has arrays but no tuples, so
Run this code in the editorjson.dumpwrites the tuple as [3, 4] andjson.loadreads it back as a list. A list never equals a tuple, so the comparison is False.printshows the loaded dict with Python's quotes, not JSON's.Question 12 · Hard
What is the output of this code?
with open("word.txt", "w") as f: f.write("python") with open("word.txt", "r+") as f: f.write("PY") with open("word.txt") as f: print(f.read())
Show the answer
Answer: A
Mode "r+" opens an existing file for reading and writing without erasing it, starting at position 0. Writing "PY" replaces the first two characters and keeps the rest. Mode "w" would have erased the file (PY), and "a" would have added to the end (pythonPY).
Run this code in the editorQuestion 13 · Easy
Which error does this code raise?
with open("notes.txt", "w") as f: f.write("Buy milk") with open("note.txt") as f: print(f.read())
Show the answer
Answer: C, FileNotFoundError: No such file or directory: 'note.txt'
Mode "r" (the default) opens only a file that already exists, and the program wrote notes.txt, not note.txt. So
Run this code in the editoropenraises FileNotFoundError. Writing modes such as "w" and "a" create a missing file; reading never does.Question 14 · Easy
Which error does this code raise?
with open("marks.txt", "w") as f: f.write("Total: ") f.write(95) with open("marks.txt") as f: print(f.read())
Show the answer
Answer: A, TypeError: write() argument must be str, not int
A file opened in text mode accepts only strings, and
Run this code in the editorwrite()does not convert numbers the wayprint()does. Passing 95 raises TypeError; writestr(95)or an f-string instead.Question 15 · Medium
What happens when this code runs?
with open("diary.txt", "w") as f: f.write("Day 1\n") f.write("Day 2\n") with open("diary.txt") as f: print(f.read())
Show the answer
Answer: B, ValueError: I/O operation on closed file.
The
Run this code in the editorwithblock closes the file as soon as it ends. The namefstill exists, but the file object behind it is closed, so the laterf.writeraises ValueError. Keep every write inside the block, or open the file again in mode "a".Question 16 · Easy
Which mode opens a text file for writing and erases anything it already holds?
Show the answer
Answer: D, 'w'
"w" creates the file if needed and truncates it to empty if it exists. "a" keeps the contents and writes at the end, "r+" keeps them and writes from the start, and "x" refuses to open a file that already exists.
Question 17 · Medium
What happens when a program runs
open("report.txt", "x")and report.txt already exists?Show the answer
Answer: D, FileExistsError is raised
Mode "x" means exclusive creation: it creates a new file for writing and raises FileExistsError if the name is taken, so existing data is never overwritten by accident. Mode "w" is the one that erases an existing file.
Question 18 · Easy
Why is
with open(...) as f:preferred to callingopen()andclose()yourself?Show the answer
Answer: B, It closes the file when the block ends, even if an error occurs
The
withstatement guarantees that the file is closed when the block is left, whether normally or because of an exception, so all written text reaches the file and the file is released. It does not change how fast or how much is read.Question 19 · Medium
notes.txt holds the lines
oneandtwo. Which code prints them on two lines with no blank line between them?Show the answer
Answer: C
Each line from the file ends with
\n, andprintadds its own newline, so the first option leaves a blank line after each one.rstrip("\n")removes the file's newline first. Looping overf.read()goes character by character, and onereadline()prints only the first line.Question 20 · Easy
Which code stores the number of lines in data.txt in
count?Show the answer
Answer: A
readlines()returns a list with one item per line, so its length is the line count.len(f.read())counts every character,len(f.readline())counts the characters of the first line only, and counting spaces has nothing to do with lines.
Keep going
- Read the lesson behind these questions: File handling in the PythonBook
- Before this: Python OOP MCQ questions with answers
- Write the code yourself in the Python coding challenges, which check your solution with tests.