10.7. Solutions to Chapter 9 Exercises#

10.7.1. Exercise 1#

Which one of the following modes of opening a file will overwrite all the contents of the file?

  1. 'w'

  2. 'a'

  3. 'r+'

The correct answer is 'w' (option 1).

10.7.2. Exercise 2#

Which mode of opening would you use for reading a file?

  1. 'r'

  2. 'a'

  3. 'r+'

The correct answer is 'r'. We can use even 'r+', but as we saw in the theoretical part it is used to open a file for reading and writing. In this case we want to open it for explicitly reading he file.

10.7.3. Exercise 3#

Which error will correspond to passing an integer to a function when the function expects a string??

  1. 'BaseError'

  2. 'ValueError'

  3. 'TypeError'

The correct answer is ValueError. Usually this error is raised when the actual value of the argument does not match with its type.

10.7.4. Exercise 4#

Write the following content into a file called 'exercise4.txt':

“In this case, no exception was raised, as a result the code block in the try statement was executed successfully. After it was finished, the control went to the finally block, printing the statement and terminating.”

# write your code here
file_path='../../files/exercise4.txt'
with open(file=file_path, mode='w') as writer_object:
    writer_object.write('In this case, no exception was raised, ' \
                        'as a result the code block in the try statement \n'\
                        'was executed successfully. After it was finished, '\
                        'the control went to the finally block, printing the \n'\
                        'statement and terminating.')

Note that you can choose another path where to store the file. In this case, the file is stored in the files folder.

10.7.5. Exercise 5#

Try to read and print in the screen the contents of the file you created in Exercise 4.

# write your code here
file_path='../../files/exercise4.txt'
with open(file=file_path, mode='r') as reader_object:
    print(reader_object.read())
In this case, no exception was raised, as a result the code block in the try statement 
was executed successfully. After it was finished, the control went to the finally block, printing the 
statement and terminating.