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' or 'a' instead of 'r' when opening a file to read.
✗ 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.
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.Trying to use
write() on a file opened for 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
Forgetting to close the file after reading.
Calling
write() on a file opened for reading.✗ Incorrect
The close() method properly closes the file to free resources.
4fill in blank
hardFill both blanks to read all lines from the file into a list.
Python
file = open('data.txt', '[1]') lines = file.[2]() file.close()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' mode which is for writing.
Using
read() which returns a string, not a list.✗ Incorrect
Open the file in read mode 'r' and use readlines() to get a list of lines.
5fill in blank
hardFill all three blanks to read the file content safely using a context manager.
Python
with open('data.txt', '[1]') as file: content = file.[2]() print([3])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' mode which is for writing.
Trying to print the file object instead of the content.
✗ Incorrect
Use 'r' mode to read, read() to get content, and print the variable content.