Working with data · 10 sample answers

Python file handling: practice questions with answers.

File questions reward precision. The mode decides whether a file is read, overwritten, or appended; the with block decides whether it is closed; the encoding decides whether non-ASCII text survives.

38 questions in the full bank · 19 choice · 15 fill · 4 output

What this topic tests

  • Choose r, w, a, and binary modes for the right job.
  • Use a with block so the file closes even when an error occurs.
  • Read lines and write text without losing newline characters.

Common mistakes

  • Using w when you meant a and accidentally truncating the file.
  • Opening a text file without an explicit encoding when the content is not ASCII.
  • Forgetting that readlines keeps newline characters at the end of each line.
Sample questions

Sample questions

10

Ten representative questions from the full bank. Try each one before opening the answer.

  1. Multiple choiceq0899

    1. Ming writes orders with open("orders.txt", "w"). What does "w" mean?

    1. read (the default mode)
    2. write (overwrite existing content)
    3. append (keep the old content)
    4. read-only (no writes allowed)
    Show answer

    Answer

    B. write (overwrite existing content)

    Why: w opens for writing and truncates the file the moment open runs, so the old ledger is gone before the first write. Use a to keep it.

  2. Multiple choiceq0906

    2. Ming writes a line, then opens the same file in another program and sees nothing. Which call pushes the buffer to disk?

    1. f.flush()
    2. f.seek(0)
    3. f.read()
    4. f.close(flush=True)
    Show answer

    Answer

    A. f.flush()

    Why: write() only hands text to the process buffer; flush() passes it to the OS, so another program sees nothing until then. close() flushes too, but only when the block ends.

  3. Multiple choiceq0913

    3. Which structure closes a file even if an exception occurs inside the block?

    1. A for loop
    2. A with statement
    3. A match statement
    4. A lambda
    Show answer

    Answer

    B. A with statement

    Why: A with block is the only structure here tied to cleanup: its __exit__ runs close() while the exception is still propagating.

  4. Multiple choiceq0918

    4. What is the main difference between f.read() and f.readlines()?

    1. they are identical
    2. the first returns one string; the second returns a list of lines
    3. the second closes the file automatically
    4. the first only reads binary
    Show answer

    Answer

    B. the first returns one string; the second returns a list of lines

    Why: read() returns the whole text as one string, while readlines() splits on newlines and keeps them, returning a list. readline() reads just one.

  5. Fill in the blankq0901

    5. Ming reads a Chinese menu file and wants to avoid garbled text. What encoding goes in open(..., encoding=___)?

    Show answer

    Answer

    utf-8

    Why: Leaving out encoding uses the platform default, often GBK on Windows; naming utf-8 decodes the bytes the way they were written.

  6. Fill in the blankq0921

    6. Append to the end of a file. Which mode goes in the blank?

    with open('orders.txt', '____', encoding='utf-8') as f:
        f.write('new\n')
    Show answer

    Answer

    a

    Why: a appends at the end, so the previous orders survive. w would erase the file first and r refuses to write. If the file is missing, a creates it, so the first append needs no special case.

  7. Fill in the blankq0928

    7. Write the header row before the data rows. Which method goes in the blank?

    writer = csv.DictWriter(f, fieldnames=['name', 'price'])
    writer.____()
    Show answer

    Answer

    writeheader

    Why: writeheader() writes fieldnames as the first CSV row. Skip it and the file starts with data, so a later DictReader reads that first data row as its header.

  8. Output predictionq0900

    8. pathlib splits a path. What are the three attributes?

    from pathlib import Path
    p = Path("data/orders.csv")
    print(p.name, p.suffix, p.parent)
    Show answer

    Answer

    orders.csv .csv data

    Why: Path splits the string without touching the disk: name is the last part with its suffix, suffix is .csv including the dot, parent is data.

  9. Output predictionq0930

    9. An in-memory file has two receipt lines. How many lines does readlines return?

    import io
    f = io.StringIO('latte,18\namericano,15\n')
    print(len(f.readlines()))
    Show answer

    Answer

    2

    Why: readlines() returns one item per newline-terminated line, so 'latte,18\n' and 'americano,15\n' yield 2. readlines() also pulls the whole file into memory, which matters once the log grows large.

  10. Output predictionq0931

    10. What is read back after writing to an in-memory file?

    import io
    f = io.StringIO()
    f.write('latte,18')
    print(f.getvalue())
    Show answer

    Answer

    latte,18

    Why: StringIO keeps the written text in memory; getvalue() returns it unchanged, with no newline added and no disk involved. It behaves like a text file.

Common questions

Why use with open instead of open and close?

The with block closes the file automatically, including when an exception interrupts the block.

What does w mode do to an existing file?

It truncates the file first. Use a to append, or r+ if you need to update without truncating.

Keep the streak going.

The full bank keeps your place in this browser, filters by topic, and includes a daily question and mistake review.

Open full practice