liveBook · Manning

Open

As explained in The Quick Python Book, Fourth Edition

open() is Python's built-in function for opening a file and returning a file object.

Use Python’s built-in open() to access a file. Its first argument is a pathname; the result is a file object, not the file’s contents. Read or write through that object’s methods. section 13.1

Choose the second argument to control access:

  • Use 'r' to read. It is the default when no mode is given. section 13.3
  • Use 'w' to write, erasing existing contents, or 'a' to append after existing contents. section 13.3

Write, then read

with open('myfile', 'w') as file_object: file_object.write('Hello, World\n') with open('myfile', 'r') as file_object: line = file_object.readline() write() needs an explicit newline in its string. readline() returns the line, including its newline if present. Using with is generally preferred because it better manages potential I/O errors. section 13.1 section 13.3 section 13.4

A relative pathname such as 'myfile' refers to the current working directory; an absolute pathname can locate a file elsewhere. os.path.join() constructs paths according to the operating system’s conventions. For text files, open() also accepts options for encoding, newline handling, and decoding errors; binary mode instead processes bytes. section 13.1 section 13.3 section 13.11 section 21.2.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains access modes and file-object use, but defers details of buffering and advanced modes.
Examples
Demonstrates reading a line from myfile, writing Hello, World, and handling invalid UTF-8 bytes.
What it assumes
Introduces file objects and pathnames from their first use without requiring prior Python file-I/O knowledge.
What you can do after
Apply it via Python’s built-in open() to read, overwrite, or append files.
How it connects
Connects file objects to context managers, path handling, and newline translation.

Also explained in

Compare how 9 books explain open →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.