Check your understanding of the previous reading: opening, reading and closing files, processing a file with a for loop, and what causes a FileNotFoundError.

Question 1

True or false: After opening a file, you should always close a file.

Select one answer, then check.

  • Correct. When you are done with a file, you should always close it with the close method: if you open a door, you need to close the door.
  • Not quite. The reading says to always close a file when you are done with it; forgetting can leak resources and possibly lose data.

Question 2

True or false: A for loop will process a file sentence-by-sentence.

Select one answer, then check.

  • Not quite. A file is a sequence of strings separated by new lines, so a for loop gives you one line at a time, not one sentence.
  • Correct. A for loop processes a file line-by-line: each line, not each sentence.

Question 3

True or false: The open function consumes a string representing a path and returns a string of the file's data.

Select one answer, then check.

  • Not quite. open does consume a path, but it returns a file object; you get the data as a string by calling read on that object.
  • Correct. open returns a file object, not the file's data; the read method returns the contents as a string.

Question 4

Given the file named grades.txt with the following contents:

90, 85, 100

And the following python code:

grade_file = open("grades.txt")
grade_data = grade_file.read()

What will be the type of grade_data?

Select one answer, then check.

  • Not quite. read doesn't split the file into lines or values; it returns the whole contents at once.
  • Not quite. Data read from a file comes in as a string, and read returns it as one piece.
  • Not quite. Data read from a file comes in as a string; you would have to convert it yourself.
  • Correct. read returns the contents of the file as a single string: "90, 85, 100".
  • Not quite. read returns the contents of the file as a single string.
  • Not quite. grade_file is the file object that open returned; grade_data holds what read returned, a string.

Question 5

Which of the following are causes of a FileNotFoundError?

Select every answer that applies, then check.

  • Correct. The file isn't where the program looks for it, so open can't find it.
  • Correct. open looks for a file with exactly that name, and there is none.
  • Not quite. There is no function opne, so Python raises a NameError before any file is looked for.
  • Not quite. open needs the path as an argument; without it Python raises a TypeError, not a FileNotFoundError.