liveBook · Manning

Open

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

open() is a Python built-in function that opens a file and returns a file object for performing input or output.

open() opens a named file and returns a file handle, which provides methods such as read(), readline(), write(), and close(). Use the handle to move data between a Python program and a file. section 5.1 section 5.2

Choose the mode according to the operation:

  • Use open(path) or open(path, 'r') to read text; reading returns a string, and a second read at the current end returns an empty string. section 5.1
  • Use 'w' or 'wt' to write text, 'a' or 'at' to append, and 'b' for bytes; write mode creates a missing file but overwrites an existing one. section 5.2
  • Close an output handle when finished; use os.path.isfile() before opening a path when a missing file would be an error. section 5.1 section 5.2

Read a file or use direct text

if os.path.isfile(args.text): args.text = open(args.text).read().rstrip() This compact pipeline opens the path, reads the entire file into a string, and removes trailing whitespace. For larger files, read() may require more memory than the file itself. section 5.5.2

Write output

out_fh = open('out.txt', 'wt') out_fh.write('this is some text\n') out_fh.close() print('this is some more text', file=out_fh) can direct output through a file handle while print() supplies the newline. section 5.2

This is our first exercise that will involve reading files. The argument to the program will be some text that might name an input file, in which case you will open and read the file. If the text is not the name of a file, you’ll use the text itself.


Use the file-or-text exercise to practice checking whether input names a file before opening and reading it. section 5.1

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains handles, modes, chaining, exhaustion, overwriting, closing, and memory costs without developing lower-level I/O internals.
Examples
Uses inputs/fox.txt, out.txt, hagrid.txt, command-line text, and inputs/exercises.csv as concrete file-processing examples.
What it assumes
Assumes basic Python expressions and paths, while teaching file handles, modes, existence checks, and input-output flow from first principles.
What you can do after
Apply it via Python to read, write, append, validate, normalize, and route text-file data in small command-line programs.
How it connects
Connects file handles with read(), readline(), write(), close(), os.path.isfile(), str.rstrip(), sys.stdout, and CSV parsing.

Also explained in

Compare how 9 books explain open →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.