Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to open a file named 'data.txt' for reading.
Python
file = open('data.txt', '[1]')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' which overwrites the file instead of reading.
Using 'a' which appends to the file instead of reading.
✗ Incorrect
The mode 'r' opens the file for reading only.
2fill in blank
mediumComplete the code to close the file object named 'file'.
Python
file.[1]() Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling
open() again instead of closing.Forgetting to close the file causing resource leaks.
✗ Incorrect
The close() method closes the file and frees resources.
3fill in blank
hardFix the error in the code to properly open a file for writing.
Python
file = open('output.txt', '[1]')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'r' mode which is for reading only.
Using 'rb' which is for reading binary files.
✗ Incorrect
The mode 'w' opens the file for writing, creating it if it doesn't exist.
4fill in blank
hardFill both blanks to open a file for appending and then close it.
Python
file = open('log.txt', '[1]') file.[2]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' instead of 'a' which overwrites the file.
Forgetting to close the file.
✗ Incorrect
Use 'a' to open the file for appending and close() to close it.
5fill in blank
hardFill all three blanks to open a file for reading, read its content, and then close it.
Python
file = open('notes.txt', '[1]') content = file.[2]() file.[3]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' mode which is for writing.
Forgetting to close the file after reading.
✗ Incorrect
Open with 'r' for reading, use read() to get content, then close() the file.