open with the mode "w" opens a file for writing. The file is created if it does not exist, and emptied if it does:
with open("report.txt", "w") as file:
file.write("Sales: 120\n")
file.write("Returns: 3\n")
write puts exactly the string it is given into the file — nothing more. Unlike print, it adds no newline; the \n characters above are what end the lines.
Reading the file back shows the result:
with open("report.txt") as file:
print(file.read())
Output:
Sales: 120
Returns: 3
Without a mode, open uses "r" — reading. Writing to a file opened for reading raises an error.
save_list with two parameters: path and items (a list of strings).path, one per line, replacing anything already there.After save_list("pets.txt", ["cat", "dog"]), the file contains cat, a newline, dog, a newline.
Run your code to see the output, then press Submit.
import unittest
class TestSaveList(unittest.TestCase):
def test_two_items_one_per_line(self):
save_list("test_pets.txt", ["cat", "dog"])
with open("test_pets.txt") as file:
self.assertEqual(file.read(), "cat\ndog\n")
def test_existing_content_is_replaced(self):
with open("test_replace.txt", "w") as file:
file.write("old content\n")
save_list("test_replace.txt", ["new"])
with open("test_replace.txt") as file:
self.assertEqual(file.read(), "new\n")
def test_empty_list_gives_empty_file(self):
save_list("test_empty.txt", [])
with open("test_empty.txt") as file:
self.assertEqual(file.read(), "")
def save_list(path, items):
with open(path, "w") as file:
for item in items:
file.write(item + "\n")
save_list("pets.txt", ["cat", "dog"])
with open("pets.txt") as file:
print(file.read())
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.