0
0
Pythonprogramming~10 mins

Why file handling is required in Python - Test Your Understanding

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'
Ar
Bw
Ca
Dx
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' or 'a' mode when you want to read a file.
2fill in blank
medium

Complete the code to write the string 'Hello' to a file named 'output.txt'.

Python
with open('output.txt', '[1]') as f:
    f.write('Hello')
Drag options to blanks, or click blank then click option'
Ar
Bw
Ca
Dx
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'r' mode when trying to write to a file.
3fill in blank
hard

Fix the error in the code to read all lines from 'log.txt'.

Python
with open('log.txt', 'r') as f:
    lines = f.[1]()
Drag options to blanks, or click blank then click option'
Areadline
Bclose
Cwrite
Dreadlines
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'readline()' when all lines are needed.
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 letters.

Python
words = ['apple', 'cat', 'banana', '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 '<' instead of '>' in the condition.
5fill in blank
hard

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

Python
words = ['tree', 'house', 'car', 'elephant']
result = { [1]: [2] for w in words if len(w) [3] 4 }
Drag options to blanks, or click blank then click option'
Aw.upper()
Blen(w)
C>
Dw.lower()
Attempts:
3 left
💡 Hint
Common Mistakes
Using w.lower() instead of w.upper().
Using '<' instead of '>'.