Vinay Garg Assistant Professor

Lesson 28: File handling: open(), access modes, close, read and write

open() connects a file on disk to a file object in your program. The mode decides whether you read, overwrite or append, and closing the file is what guarantees the data reached the disk.

A dark code window opening a file for writing and reading it back

In short

  • `open(path, mode)` returns a file object; the common modes are `r`, `w`, `a` and `rb`.
  • `"w"` empties the file first, so opening an existing file for writing destroys it.
  • `write()` does not add a newline; include `"\n"` yourself.
  • `with open(...) as f:` closes the file even if an error occurs, which is why it is the recommended form.

4

basic modes: r, w, a, x

Python docs

0

newlines added automatically by write()

Python docs

What a file object is

open() asks the operating system for a file and gives you a file object — a handle you read from or write through. Nothing is written until you ask, and nothing is guaranteed to reach the disk until the file is closed.

The program

# files.py — write, read, append

f = open("notes.txt", "w")
print(f.name, f.mode, f.closed)     # notes.txt w False
f.write("First line\n")
f.write("Second line\n")
f.close()
print(f.closed)                     # True

f = open("notes.txt", "r")
content = f.read()
f.close()
print(content)

with open("notes.txt", "a") as f:
    f.write("Third line\n")

with open("notes.txt", "r") as f:
    for line in f:
        print(line.strip())

How it works, step by step

  1. open("notes.txt", "w") creates the file if it does not exist, or empties it if it does.
  2. f.name, f.mode and f.closed are attributes describing the open file.
  3. write() puts exactly the characters you give it. Without "\n" the next write continues on the same line.
  4. close() flushes the buffer and releases the file. f.closed then becomes True.
  5. Reading with read() returns the whole file as one string.
  6. The with block opens in append mode, adds a line, and closes automatically — even if an exception happens inside.

What it prints

notes.txt w False
True
First line
Second line

First line
Second line
Third line

Access modes

ModeMeansIf the file existsIf it does not
"r"ReadOpens at the startFileNotFoundError
"w"WriteEmpties itCreates it
"a"AppendWrites at the endCreates it
"x"CreateFileExistsErrorCreates it
"r+"Read and writeOpens without emptyingFileNotFoundError
"rb", "wb"BinaryImages, PDFs, anything not textas above

Reading in three ways

  • f.read() — everything as one string.
  • f.readline() — one line, including its newline.
  • f.readlines() — a list of lines.

For a large file, the for line in f: form used above is best: it reads one line at a time instead of loading the whole file into memory.

Common mistakes

  • Opening with "w" when you meant "a", and losing the previous contents.
  • Forgetting \n in write(), then finding every line joined together.
  • Reading and writing the same file at once. Read it, close it, then write.
  • Leaving the file open. Use with so it closes on every path out.

Practice

Try these before moving on. Each one uses only what this lesson covered.

  1. Program 16: use `open()`, `write()` and `read()` to save two lines to a file and print them back.
  2. Append a third line to the same file in append mode and print the whole file.
  3. Print `f.name`, `f.mode` and `f.closed` before and after closing a file.
  4. Read a file line by line with a `for` loop and print each line without the trailing newline.

Sources

Frequently asked questions

What does open() do in Python?

It opens a file and returns a file object you can read from or write through. The mode argument decides which: r reads, w overwrites, a appends.

What is the difference between w and a mode?

w empties the file before writing, so the old contents are lost. a keeps the contents and writes at the end. Choosing the wrong one is the most common file-handling bug.

Why should I use with open(...) as f?

Because it closes the file automatically, even when an exception happens inside the block. With a manual open you must remember close() on every path.

Does write() add a newline?

No. It writes exactly what you give it, so include "\n" when you want the next write on a new line.

Vinay Garg

Vinay Garg

Assistant Professor of Computer Science at Multani Mal Modi College, Patiala. Twenty-five years of teaching web programming, and a habit of building the things I teach about.