Chapter Review Questions

Chapter Review Questions#

Note

Source: Adapted from the C# edition (files/reviewfiles.rst). Questions about StreamReader/StreamWriter are replaced by Python open() and with statement equivalents.

  1. The with statement and open().

    1. What does the with statement do when used with open()?

    2. Why is this preferable to calling f.close() manually?

  2. What mode string do you pass to open() to write to a file? What happens if the file already exists?

  3. What mode string do you pass to open() to append to an existing file?

  4. Iterating over lines.

    1. In a for line in f: loop, does each line string include the trailing newline character?

    2. How do you remove it?

  5. Two ways to read a file.

    1. What does f.read() return?

    2. What does f.readlines() return?

    3. When would you prefer each?

  6. Write a cross-platform path for the file data.txt located in a subdirectory called input of the current directory, using pathlib.Path.

  7. What does .. mean in a relative path?

  8. In the path Path("a") / "b" / "c.txt", what is returned by:

    1. .name

    2. .stem

    3. .suffix

    4. .parent

  9. What method checks whether a path points to an existing file?

  10. What is logically wrong with the following code?:

    with open("data.txt") as f:
        first = f.readline()
        if "error" in f.readline():
            print("Error on line:", f.readline())