0
0
Pythonprogramming~10 mins

Appending data to files 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 'log.txt' in append mode.

Python
file = open('log.txt', '[1]')
Drag options to blanks, or click blank then click option'
Ar
Ba
Cw
Dx
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' mode which overwrites the file.
Using 'r' mode which is read-only.
2fill in blank
medium

Complete the code to write the string 'Hello\n' to the file object named 'file'.

Python
file.[1]('Hello\n')
Drag options to blanks, or click blank then click option'
Awrite
Bread
Cappend
Dopen
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to use a method named 'append' which does not exist.
Using 'read' which is for reading, not writing.
3fill in blank
hard

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

Python
file = open('log.txt', 'a')
file.write('Data\n')
file.[1]()
Drag options to blanks, or click blank then click option'
Aopen
Bflush
Cclose
Dwrite
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'flush' instead of 'close' which does not close the file.
Calling 'open' again instead of closing.
4fill in blank
hard

Fill both blanks to append the number 5 as a string to the file 'numbers.txt'.

Python
with open('numbers.txt', '[1]') as f:
    f.[2]('5\n')
Drag options to blanks, or click blank then click option'
Aa
Bw
Cwrite
Dappend
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' mode which overwrites the file.
Trying to use a method named 'append' which does not exist.
5fill in blank
hard

Fill all three blanks to append squares of numbers 1 to 3 to 'squares.txt', each on a new line.

Python
with open('squares.txt', '[1]') as f:
    for i in range(1, 4):
        f.[2](str(i[3]2) + '\n')
Drag options to blanks, or click blank then click option'
Aa
Bwrite
C**
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Using '*' instead of '**' for exponentiation.
Using 'w' mode which overwrites the file.