Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Modules, Files and Errors

Read and Write a File in Python: open, with, Modes and Encoding

Make your data outlive the program: write notes.txt with open and with, read it back three ways, see how w wipes a file and a appends, why encoding matters, and what to do when a file isn't there.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Modules, Files and Errors

What you will learn

  • Open a file with with open() and know it closes for you
  • Choose the right mode: r reads, w starts fresh, a adds to the end
  • Read a file with read(), readlines() or a for loop
  • Use encoding="utf-8", handle FileNotFoundError, and understand relative paths

Before you start

  • Python basics: strings, lists and loops
  • try and except basics

Right now your program keeps its data in variables, and when the program ends all of that is gone. A file is more like a notebook on a shelf. The program ends, and the notebook's still there. You use it the same way every time: take it down, read or write, put it back. In Python that's open, do the work, close.

Writing a file

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Buy milk\n")
    f.write("Call Sam\n")

print("saved")
saved

open takes three things here:

  • The file name, notes.txt.
  • The mode, which says what you want to do. "w" is write, "r" is read, and "a" adds to the end.
  • encoding="utf-8", which we'll come back to.

open hands you a file object, and as f gives it a short name. f.write puts text in the file. The \n is the new line; write doesn't add one for you. When the indented block ends, with closes the file, so you can't forget, even if something goes wrong inside the block. After the run, notes.txt appears in the project. It wasn't there before, so w created it.

Reading it back

with open("notes.txt", "r", encoding="utf-8") as f:
    text = f.read()

print(text)
print(len(text))
Buy milk
Call Sam

18

f.read() takes the whole file and gives you one string. The blank line appears because the text already ends with a new line and print adds one more. The length is 18: each line has nine characters, because the new line counts as one.

Is the file really closed?

with open("notes.txt", encoding="utf-8") as f:
    text = f.read()

print(f.closed)
print(text)
True
Buy milk
Call Sam

"r" is the default mode, so you can leave it out. Outside the block, f.closed is True, but text still has the two lines because it's an ordinary string in memory now. Do the file work inside the block and use the result anywhere.

Three ways to read

Sometimes you want a list, one item per line:

with open("notes.txt", encoding="utf-8") as f:
    lines = f.readlines()

print(lines)
print(len(lines))
['Buy milk\n', 'Call Sam\n']
2

Each item still has its \n. Most of the time you don't need the whole file at once. The file object goes straight into a for loop:

with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print("Task:", line.strip())
Task: Buy milk
Task: Call Sam

strip() takes the new line off each one. Python reads one line each time round, so this is the normal way to go through a file, and it works the same on a file far bigger than memory.

CallGives you
f.read()the whole file as one string
f.readlines()a list, one string per line, each ending in \n
for line in fone line at a time

Always say encoding="utf-8"

A file only stores bytes, so Python needs a rule to turn text into bytes and back. That rule is the encoding.

with open("menu.txt", "w", encoding="utf-8") as f:
    f.write("café\n")

with open("menu.txt", encoding="utf-8") as f:
    line = f.read().strip()

print(line)
print(len(line))
café
4

Reading with the same encoding gives you the same word back, and its length is 4 characters. If you leave the encoding out, Python uses your computer's default, and that can differ from one machine to another. For text files, always write encoding="utf-8". It saves you from strange characters later.

w starts fresh, a adds to the end

Opening log.txt with mode w empties it the moment it opens, so writing three leaves only three. Opening with mode a keeps three and writing four adds it at the end. open("log.txt", "w") one two three old lines gone on open open("log.txt", "a") three three four kept, new line at the end Use w only when you mean "start this file again".
One letter decides whether the old content survives.
with open("log.txt", "w", encoding="utf-8") as f:
    f.write("one\n")
    f.write("two\n")

with open("log.txt", "w", encoding="utf-8") as f:
    f.write("three\n")

with open("log.txt", encoding="utf-8") as f:
    print(f.read(), end="")
three

The moment the second open with "w" runs, the old content is gone, before anything is written. If the file holds something you need, w isn't the mode you want. To keep what's there, use "a":

with open("log.txt", "a", encoding="utf-8") as f:
    f.write("four\n")

with open("log.txt", encoding="utf-8") as f:
    print(f.read(), end="")
three
four

That's what you want for logs and notes.

When the file isn't there

with open("missing.txt", encoding="utf-8") as f:
    print(f.read())

print("Done")
Traceback (most recent call last):
  File "S04L00_2_Files\missing_file.py", line 1, in <module>
    with open("missing.txt", encoding="utf-8") as f:
         ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'

You already have the fix from try and except basics. Put the whole with block inside try:

try:
    with open("missing.txt", encoding="utf-8") as f:
        print(f.read())
except FileNotFoundError:
    print("No such file yet")

print("Done")
No such file yet
Done

The program carries on, and reading doesn't create a file.

Where Python looks: relative paths

Just notes.txt is a relative path. It's relative to the folder the program is running from, the working directory.

import os

print(os.path.exists("notes.txt"))
True

Run from the project folder, it prints True. Move into a folder called elsewhere, one level down, and run the same file from there: it prints False. Same code, same name, but Python is looking in a different folder. If a file you can see gives you "not found", check which folder you're running from. The next step, context managers and pathlib, builds paths that don't depend on that.

Quick recap

  • with open(...) as f gives you a file and closes it for you.
  • r reads, w starts fresh (wipes it), a adds to the end.
  • read() gives one string, readlines() a list, a for loop one line at a time.
  • Use encoding="utf-8", and catch FileNotFoundError when a file might not be there.

Try it yourself

Open notes.txt in a mode, add the line "Pay rent", then read the file back and print every line. You should see three lines:

Buy milk
Call Sam
Pay rent

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 28 of 48

Previous
Python try and except Basics: Catch an Error and Keep Going
Next post
Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Set Up a Python AI Project with uv, VS Code and an API Key in .env

One environment for every AI project: uv brings Python 3.12 and pinned packages from uv.lock, a check script fails four times on plain python and passes after uv sync, VS Code points at .venv, the API key stays in .env, and a stand-in test model answers when there is no key.

uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project

One tool instead of venv, activate, pip install and pip freeze. Build a small chatbot project with uv init, hit ModuleNotFoundError, fix it with uv add, read pyproject.toml and uv.lock, then delete .venv and rebuild it with uv sync.

Python try and except Basics: Catch an Error and Keep Going

An exception is the object Python creates when something goes wrong. Catch it with try and a named except, read it with as, add else and finally, retry bad input in a loop, and see why a bare except hides your bugs.

Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack

raise sends an error and except receives it. Follow an error up the call stack, use the exception family tree, re-raise and chain errors with raise from, and build InsufficientFundsError and an AppError family of your own.

On this page

  • Writing a file
  • Reading it back
  • Is the file really closed?
  • Three ways to read
  • Always say encoding="utf-8"
  • w starts fresh, a adds to the end
  • When the file isn't there
  • Where Python looks: relative paths
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.