Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to open a file named 'log.txt' in append mode.
Python
file = open('log.txt', '[1]')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' mode which overwrites the file.
Using 'r' mode which is read-only.
✗ Incorrect
To add data to the end of a file without deleting existing content, use mode 'a' for append.
2fill in blank
mediumComplete the code to write the string 'Hello\n' to the file object named 'file'.
Python
file.[1]('Hello\n')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to use a method named 'append' which does not exist.
Using 'read' which is for reading, not writing.
✗ Incorrect
The write method adds text to the file.
3fill in blank
hardFix the error in the code to properly close the file after writing.
Python
file = open('log.txt', 'a') file.write('Data\n') file.[1]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'flush' instead of 'close' which does not close the file.
Calling 'open' again instead of closing.
✗ Incorrect
Always close a file after writing to save changes and free resources.
4fill in blank
hardFill both blanks to append the number 5 as a string to the file 'numbers.txt'.
Python
with open('numbers.txt', '[1]') as f: f.[2]('5\n')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' mode which overwrites the file.
Trying to use a method named 'append' which does not exist.
✗ Incorrect
Open the file in append mode 'a' and use the write method to add text.
5fill in blank
hardFill all three blanks to append squares of numbers 1 to 3 to 'squares.txt', each on a new line.
Python
with open('squares.txt', '[1]') as f: for i in range(1, 4): f.[2](str(i[3]2) + '\n')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '*' instead of '**' for exponentiation.
Using 'w' mode which overwrites the file.
✗ Incorrect
Open in append mode 'a', use write to add text, and use '**' to square the number.