Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python file I/O code

Practice opening, reading, writing, appending, and selecting text or binary file modes.

Intermediate ~8 min read

Challenge 1

Open path for UTF-8 text reading and read all its contents.

python Your answer
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / 'note.txt'
    path.write_text('hello', encoding='utf-8')
    with open(path, ) as file:
        result = file.read()
    print(result)

Press Ctrl⌘Enter to check your answer

Challenge 2

Open path for UTF-8 text writing, replacing any existing contents.

python Your answer
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / 'note.txt'
    with open(path, ) as file:
        file.write('hello')

Press Ctrl⌘Enter to check your answer

Challenge 3

Open path so the new line is added after existing contents.

python Your answer
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / 'log.txt'
    path.write_text('first\n', encoding='utf-8')
    with open(path, ) as file:
        file.write('second\n')

Press Ctrl⌘Enter to check your answer

Challenge 4

Open path for writing raw bytes.

python Your answer
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / 'data.bin'
    with open(path, ) as file:
        file.write(b'ABC')

Press Ctrl⌘Enter to check your answer