0
0
Pythonprogramming~10 mins

Reading file data in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Aw
Ba
Cr
Dx
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' or 'a' instead of 'r' when opening a file to read.
2fill in blank
medium

Complete 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'
Aread
Bclose
Cwrite
Dreadline
Attempts:
3 left
💡 Hint
Common Mistakes
Using readline() which reads only one line.
Trying to use write() on a file opened for reading.
3fill in blank
hard

Fix 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'
Aread
Bclose
Copen
Dwrite
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to close the file after reading.
Calling write() on a file opened for reading.
4fill in blank
hard

Fill 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'
Ar
Bread
Creadlines
Dw
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' mode which is for writing.
Using read() which returns a string, not a list.
5fill in blank
hard

Fill 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'
Ar
Bread
Ccontent
Dw
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' mode which is for writing.
Trying to print the file object instead of the content.