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 opens the file for writing and erases content.
Using 'a' which opens the file for appending.
✗ Incorrect
The mode 'r' opens the file for reading.
2fill in blank
mediumComplete the code to read the entire content of the file into a variable named 'content'.
Python
content = file.[1]() Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
readline() which reads only one line.Using
write() which is for writing, not reading.✗ Incorrect
The read() method reads the whole file content as a string.
3fill in blank
hardFix the error in the code to properly close the file after reading.
Python
file = open('data.txt', 'r') content = file.read() file.[1]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling
read() again instead of closing.Trying to open the file again instead of closing.
✗ Incorrect
After finishing file operations, always close the file using close().
4fill in blank
hardFill both blanks to read the entire file content safely using a context manager.
Python
with open('data.txt', '[1]') as file: content = file.[2]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' mode which is for writing.
Using
write() method which is for writing.✗ Incorrect
Using with open(..., 'r') opens the file for reading and automatically closes it. Then read() reads all content.
5fill in blank
hardFill all three blanks to read the file content and print it.
Python
with open('[1]', '[2]') as file: content = file.[3]() print(content)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong file name or mode.
Using
write() instead of read().✗ Incorrect
The file name is 'data.txt', mode is 'r' for reading, and read() reads the entire content to print.