0
0
Pythonprogramming~10 mins

Reading files line by line 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' which opens the file for writing and erases content.
Using 'a' which opens the file for appending.
2fill in blank
medium

Complete the code to read the first line from the file object 'file'.

Python
line = file.[1]()
Drag options to blanks, or click blank then click option'
Awrite
Breadline
Creadlines
Dread
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'read' which reads the whole file content.
Using 'write' which is for writing, not 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'
Aclose
Bclosed
Cclose()
Dclose_file
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'close()' inside the blank which would cause syntax error.
Using 'closed' which is a property, not a method.
4fill in blank
hard

Fill both blanks to create a dictionary with words as keys and their lengths as values, only for words longer than 3 characters.

Python
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: [1] for word in words if len(word) [2] 3}
Drag options to blanks, or click blank then click option'
Alen(word)
B>
C<
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as value instead of its length.
Using '<' instead of '>' in the condition.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase words as keys and their lengths as values, only for words longer than 3 characters.

Python
words = ['apple', 'bat', 'carrot', 'dog']
result = { [1]: [2] for word in words if len(word) [3] 3 }
Drag options to blanks, or click blank then click option'
Aword.upper()
Blen(word)
C>
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as key instead of uppercase.
Using '<' instead of '>' in the condition.