Reading and writing files

Reading and writing text files in Python: opening for reading, writing or appending, reading whole or line by line, writing, closing, relative or absolute path, line endings and opening errors.

  • 27 cards
  • 5 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. Understand

A few cards from the deck

  • Text file: what is it?

    Show the answer

    A sequence of characters stored on disk, which a program reads and writes line by line, and which a text editor can display.

    A file of marks with one number per line is a text file: 12 is read as the string '12\n', and it must be converted before computing.

  • What does notes.txt contain at the end of this program?

    ```python
    with open("notes.txt", "w") as f:
    f.write("12\n")
    with open("notes.txt", "w") as f:
    f.write("15\n")
    with open("notes.txt", "a") as f:
    f.write("9\n")
    `

    • Two lines: 15, then 9
    • Three lines: 12, 15, then 9
    • A single line: 15
    • Two lines: 12, then 9
    Show the answer

    Two lines: 15, then 9

    Each opening in 'w' empties the file: the 12 disappears at the second opening. Opening in 'a' keeps the 15 and adds the 9 after it.

  • Opening an existing file in mode w … its contents; in mode a, you ….

    Show the answer

    Opening an existing file in mode w erases its contents; in mode a, you add at the end.

    The erasing takes place on opening, before the first write. To keep the old contents, open in mode 'a'.

  • Open mode: what is it?

    Show the answer

    A short code, most often one letter, given when a file is opened, which says what you are allowed to do with it: read it, write it starting from scratch, or add to its end.

    'r' reads, 'w' erases then writes, 'a' adds at the end. The default mode is 'r': open("notes.txt") can neither create the file nor write to it.

  • Your program opens "data/notes.txt" and works from your editor, but fails with FileNotFoundError when run from another folder. Why?

    • Python only finds files in the folder where the .py file is
    • The path starts from the launch folder, which has changed
    • The file is destroyed when the editor is closed
    • The data subfolder only exists in read mode
    Show the answer

    The path starts from the launch folder, which has changed

    A relative path starts from the launch folder, not from the .py file's location. Either always run from the same folder, or build an absolute path from the program's location.