Editor

Python file handling MCQ questions with answers

Open modes, reading, writing and the with statement: the file questions CBSE asks.

0 of 20 answered

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

    write() adds exactly the text it is given: no space and no newline. The two calls put HelloWorld on one line; add \n yourself where a line should end. Both calls happen in the same with block, so the second one does not replace the first.

    Run this code in the editor
  2. 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. split() with no argument splits on any whitespace, newlines included, and drops it. Mode "w" in the second open would have erased "one".

    Run this code in the editor
  3. 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

    read() returns the whole file as one string, and split() breaks it on spaces and newlines alike, giving six words, two of which are "the". 2 would be the number of lines, which is what len(f.readlines()) counts.

    Run this code in the editor
  4. 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

    readline() returns one line including its \n, and print adds another newline, so a blank line follows the first line. The second readline() continues from where the first stopped, giving the second line, and end="" stops print adding a newline of its own.

    Run this code in the editor
  5. 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

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

    Run this code in the editor
  6. 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

    read(3) reads three characters and leaves the position at 3, which tell() reports (positions count from 0). seek(1) moves back to the second character, so read(2) gives BC. Reading on without the seek would have given DE.

    Run this code in the editor
  7. 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, writelines() does not add newlines: it writes each string as it is, one after another. The file holds peninknib on a single line, so readlines() returns a list with one item.

    Run this code in the editor
  8. 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

    csv.writer turns each list into one comma-separated line, and csv.reader gives each line back as a list of strings. A CSV file stores only text, so the number 91 comes back as '91'; convert it with int() when you need a number.

    Run this code in the editor
  9. 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 write() the position is at the end of the file, so the first read() returns an empty string. seek(0) moves back to the start and the second read gets the text; split() gives strings, not numbers.

    Run this code in the editor
  10. 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 \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.

    Run this code in the editor
  11. 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 json.dump writes the tuple as [3, 4] and json.load reads it back as a list. A list never equals a tuple, so the comparison is False. print shows the loaded dict with Python's quotes, not JSON's.

    Run this code in the editor
  12. 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 editor
  13. Question 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 open raises FileNotFoundError. Writing modes such as "w" and "a" create a missing file; reading never does.

    Run this code in the editor
  14. 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 write() does not convert numbers the way print() does. Passing 95 raises TypeError; write str(95) or an f-string instead.

    Run this code in the editor
  15. 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 with block closes the file as soon as it ends. The name f still exists, but the file object behind it is closed, so the later f.write raises ValueError. Keep every write inside the block, or open the file again in mode "a".

    Run this code in the editor
  16. 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.

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

  18. Question 18 · Easy

    Why is with open(...) as f: preferred to calling open() and close() yourself?

    Show the answer

    Answer: B, It closes the file when the block ends, even if an error occurs

    The with statement 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.

  19. Question 19 · Medium

    notes.txt holds the lines one and two. 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, and print adds its own newline, so the first option leaves a blank line after each one. rstrip("\n") removes the file's newline first. Looping over f.read() goes character by character, and one readline() prints only the first line.

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