Writing Files

Writing Files

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.

Exercise

  1. Define a function named save_list with two parameters: path and items (a list of strings).
  2. It writes the items to the file at 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.

Tests

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())
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.