Week 4 Assignment (Part 1 - Questions)
22. October 2024
Question 1
Which of the following statements about file handling in Python are correct?
Note: There are 3 correct answers to this question.
Files can be used to share data between different programs.
✅Files must only contain the normal characters and digits.
❌Files must have a name, otherwise they are not "callable".
✅The rules for naming a file are the same as the rules for naming variables.
❌Using files, data can be stored persistently, in other words, when the program is stopped or when the computer is switched off, the data is still available.
✅Question 2
Which statements about the following code are correct?
Note: There are 2 correct answers to this question.
In this case, it does not matter that the ".close()" method is not executed, as the file is read only.
❌When a file is opened with the "with" statement, it is not necessary to close it. This is done automatically at the end of the "with" block.
✅The file will not be stored correctly at the end of the program because it is not closed correctly.
❌Using the "with" statement in combination with the "open" function limits the number of faults, as the closing of the file is done implicitly.
✅Using the "with" statement, it does not matter if the file "first_file.txt" exists. In case there is no such file, the program will simply continue and does not raise an error.
❌Question 3
Which statements regarding the following program are correct?
Note: There are 2 correct answers to this question.
The line breaks "\n" at the end of each line in the file are automatically deleted by the �with� statement.
❌The file is not closed correctly at the end of the program.
❌After the program is executed, the variable "line" is a list.
✅If the file "lorem_ipsum.txt" does not exist, the program stops with an error.
✅Only the first line of the file is read into the variable "line".
❌Question 4
Which of the following statements about the .strip()
method are correct?
Note: There are 2 correct answers to this question.
Using the string method ".strip()", leading and ending spaces, tabs, line breaks, and so on, are deleted.
✅To loop through the lines of a file and first ".strip()" the line is a common pattern when dealing with files.
✅If a file contains only digits, the ".strip()" method cannot be used, as it only works on strings.
❌The method ".lstrip()" can be used on integers to delete leading zeros.
❌It is better to use the ".strip()" method multiple times (for example, "string.strip().strip()"), because then even double spaces are deleted.
❌Question 5
The following program is intended to write the numbers from 1 to 10 to a file. The numbers should be stored in subsequent lines. What mistakes does the program contain?
Note: There are 2 correct answers to this question.