Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new file in the temporary directory using tmp_path.
PyTest
def test_create_file(tmp_path): file = tmp_path / [1] file.write_text("Hello") assert file.read_text() == "Hello"
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put quotes around the file name.
Using a variable name without quotes.
✗ Incorrect
The file name must be a string, so it needs to be in quotes like "test.txt".
2fill in blank
mediumComplete the code to check if the file exists after creation.
PyTest
def test_file_exists(tmp_path): file = tmp_path / "data.txt" file.write_text("data") assert file.[1]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using is_file() which checks if it is a file but not if it exists.
Using is_dir() which checks for directories.
✗ Incorrect
The method exists() checks if the file exists in the path.
3fill in blank
hardFix the error in the code to write and read text from a file using tmp_path.
PyTest
def test_write_read(tmp_path): file = tmp_path / "log.txt" file.[1]("Test log") content = file.read_text() assert content == "Test log"
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using write() which is not a method of Path objects.
Using write_bytes() which expects bytes, not string.
✗ Incorrect
write_text() writes string content directly to the file.
4fill in blank
hardFill both blanks to create a subdirectory and check if it is a directory.
PyTest
def test_subdir(tmp_path): subdir = tmp_path / [1] subdir.[2]() assert subdir.is_dir()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using makedirs() which is not a method of Path objects.
Not putting the folder name in quotes.
✗ Incorrect
Use a string for the folder name and mkdir() to create the directory.
5fill in blank
hardFill all three blanks to create a file, write text, and verify its size is greater than zero.
PyTest
def test_file_size(tmp_path): file = tmp_path / [1] file.[2]("content") assert file.stat().st_size [3] 0
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > for size comparison.
Forgetting quotes around the file name.
✗ Incorrect
Create a file named "output.txt", write text with write_text(), and check size > 0.