0
0
Pythonprogramming~10 mins

Writing 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 'output.txt' for writing.

Python
file = open('output.txt', '[1]')
Drag options to blanks, or click blank then click option'
Aw
Bx
Ca
Dr
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'r' mode which is for reading only.
Using 'a' which appends instead of overwriting.
2fill in blank
medium

Complete the code to write the string 'Hello, world!' to the file.

Python
file.write('[1]')
Drag options to blanks, or click blank then click option'
AHello world!
BHello, world!
Chello, world!
DHello world
Attempts:
3 left
💡 Hint
Common Mistakes
Missing the comma or exclamation mark.
Using lowercase 'hello' instead of capital 'Hello'.
3fill in blank
hard

Fix the error in the code to properly close the file after writing.

Python
file.[1]()
Drag options to blanks, or click blank then click option'
Aclosing
Bclosed
Cclose
Dclose_file
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'closed' which is an attribute, not a method.
Using 'closing' or 'close_file' which are invalid.
4fill in blank
hard

Fill both blanks to write 'Python' followed by a newline to the file.

Python
file.write('[1]'[2]'\n')
Drag options to blanks, or click blank then click option'
APython
BPython\n
C+
D,
Attempts:
3 left
💡 Hint
Common Mistakes
Using ',' which does not concatenate strings.
Putting the newline inside the first blank without concatenation.
5fill in blank
hard

Fill all three blanks to write each word in the list to the file on separate lines.

Python
words = ['apple', 'banana', 'cherry']
for [1] in words:
    file.write([2] + [3])
Drag options to blanks, or click blank then click option'
Aword
C'\n'
Dwords
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'words' as the loop variable which is the list itself.
Forgetting to add the newline character.