Reading Files

Reading Files

open opens a file; the file object's read method returns its entire content as one string:

file = open("notes.txt")
content = file.read()
file.close()
print(content)

Every opened file must be closed. The with statement does it automatically — the file closes when the indented block ends, even if an error occurs inside:

with open("notes.txt") as file:
    content = file.read()
print(content)

This is the standard form. Use it every time; the manual close version above is shown only so you recognize it.

Opening a file that does not exist raises FileNotFoundError.

In this editor, files live in a private sandbox. Your code can create files and read them back; they disappear when the page reloads.

Exercise

  1. Define a function named read_note with one parameter, path.
  2. It opens the file at path with a with statement, reads it, and returns the content with surrounding whitespace stripped.

The starter code writes a small file first so Run has something to read.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestReadNote(unittest.TestCase):
    def setUp(self):
        with open("test_note.txt", "w") as file:
            file.write("  remember the eggs \n")

    def test_content_is_returned_stripped(self):
        self.assertEqual(read_note("test_note.txt"), "remember the eggs")

    def test_other_file_other_content(self):
        with open("test_other.txt", "w") as file:
            file.write("hello\n")
        self.assertEqual(read_note("test_other.txt"), "hello")
def read_note(path):
    with open(path) as file:
        return file.read().strip()


with open("note.txt", "w") as file:
    file.write("Buy milk\n")

print(read_note("note.txt"))
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.