liveBook · Manning

File object

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

A file is a named, persistent container of data managed by a filesystem.

A file is a named container for persistent text data. Python opens it through a file handle, which lets programs read, write, append, or print text. section 5.2 section 5.5.2

Choose an opening mode that matches the operation:

  • Use r to read, w to write and replace existing contents, or a to append. section 5.2
  • Combine an operation with t for text or b for binary content, such as wt or rb. section 5.2
  • Use read() to obtain the entire file as one string, and close() when finished. section 5.2 section 5.5.2

Writing and reading a text file

fh = open('hagrid.txt', 'wt') fh.write("I am what I am an' I'm not ashamed.\n") fh.close() text = open('hagrid.txt').read() print(text) section 5.2

Command-line programs can accept either literal text or a filename. Check with os.path.isfile(), read a matching file, and strip its trailing whitespace so both inputs behave consistently. section 5.5.2

Table 5.1 File-writing modes (view table figure)

Mode

Meaning

w

Write

r

Read

a

Append

Browse the file-writing mode table for the meanings of w, r, and a. section 5.2

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

How deep it goes
Explains handles, modes, read/write methods, closing, newline behavior, and memory limits while stopping short of large-file techniques.
Examples
Demonstrates Howler transformations, out.txt output, hagrid.txt writing, and file-based text processing tests.
What you can do after
Build Python programs that read text files, write or append output, and distinguish filenames from literal command-line text.
How it connects
Connects files with file handles, command-line arguments, standard output, strings, and input normalization.

Also explained in

Compare how 8 books explain file object →

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.