Lesson 36 of 60
โฎPrev Nextโฏ

PY-101 ยท Files and errors

Reading and writing files

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

36of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก The 30-second answer

    open(name, mode) opens a file: "w" writes (replacing what was there), "a" appends to the end and "r" reads. Use .write() to save text and .read() or a for loop to read it back. Files hold text, so convert numbers with str() before writing.

    • Write and append to a file
    • Read a whole file or line by line
    • Know the w, a and r modes

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    Reading and writing files, running
    1. with open("tasks.txt", "w") as f:
    2. f.write("Buy milk\n")
    3. f.write("Call Ravi\n")
    4. with open("tasks.txt", "a") as f:
    5. f.write("Learn Python\n")
    6. with open("tasks.txt") as f:
    7. for number, line in enumerate(f, start=1):
    8. print(number, line.strip())
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemYour to-do app forgets everything when you close it. To remember tasks between runs, the program has to write them to a file and read them back next time.
    2. The Python ideawith open("file.txt", "w") as f:open(name, mode) opens a file: "w" writes (replacing what was there), "a" appends to the end and "r" reads.
    3. In real lifeServers append a line to a log file for every request, and engineers read those logs when something breaks.

    Start with a question

    Your to-do app forgets everything when you close it. To remember tasks between runs, the program has to write them to a file and read them back next time.

    Saving settings, logs, reports and exports all means writing files. Reading them is how scripts process data.

    Explain it like I'm 10

    A file is a notebook the program keeps in a drawer. "w" tears out the old pages and starts fresh, "a" adds to the last page, "r" just reads.

    The technical explanation

    with open("notes.txt", "w") as f: f.write("text\n") creates or replaces the file. \n ends a line.

    with open("notes.txt") as f: text = f.read() reads it all. for line in f: reads one line at a time.

    In this course the code runs in a private file system inside your browser, so nothing touches your computer.

    Syntax

    with open("file.txt", "w") as f:
        f.write("text\n")
    with open("file.txt") as f:
        for line in f: ...

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    Servers append a line to a log file for every request, and engineers read those logs when something breaks.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. Which mode adds to the end of a file?
    2. 2. What does "w" do to an existing file?
    3. 3. What does f.read() return?
    4. 4. Can you write the number 5 directly with f.write(5)?
    5. 5. What does \n add when writing?

    Questions people ask

    What is the difference between read(), readline() and readlines()?

    read() returns the whole file as one string, readline() the next line, readlines() a list of all lines. Looping with for line in f is the most memory-friendly way.

    Why should I specify encoding when opening files?

    Different computers use different default encodings. open(name, encoding="utf-8") makes sure text like โ‚น or รฉ reads the same everywhere.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner What is the difference between read(), readline() and readlines()?

    read() returns the whole file as one string, readline() the next line, readlines() a list of all lines. Looping with for line in f is the most memory-friendly way.

    beginner Why should I specify encoding when opening files?

    Different computers use different default encodings. open(name, encoding="utf-8") makes sure text like โ‚น or รฉ reads the same everywhere.

    intermediate Which mode adds to the end of a file?

    "a". "a" appends.

    intermediate What does "w" do to an existing file?

    Replaces its contents. Write mode starts the file again.

    Quick revision

    Remember

    • Write and append to a file
    • Read a whole file or line by line
    • Know the w, a and r modes
    • "w" wipes the file first. If you meant to add, use "a", or you will lose yesterday's data.

    Syntax

    with open("file.txt", "w") as f:
        f.write("text\n")
    with open("file.txt") as f:
        for line in f: ...

    Official documentation