liveBook · Manning

I/O

As explained in The Quick Python Book, Fourth Edition

I/O is the transfer of data into and out of a program through streams, files, devices, or other interfaces.

I/O transfers data into and out of a Python program through file objects, terminal streams, paths, devices, and related interfaces. Text is the default file representation; binary mode processes bytes. section 13.11 section 13.6

Use the appropriate interface for the data source or destination:

  • Read interactive input with input(); its optional prompt is written to standard output, the entered line loses its final newline, and the result is always a string. section 13.6
  • Convert input explicitly when a numeric value is required, such as int(input("enter your number: ")). Invalid conversion raises an exception. section 13.6
  • Access lower-level streams through sys.stdin, sys.stdout, and sys.stderr, which behave as specialized file objects with methods including read, readline, readlines, write, and writelines. section 13.6
  • Redirect output by assigning a writable file to sys.stdout, pass file=f to print(), or restore the original stream with sys.__stdout__. section 13.6
  • Use pathlib paths for platform-aware text or binary file access; use struct for packed binary formats, pickle for complex structures, and shelve for dictionary-like persistence with string keys. section 13.11 section 12.0

Capture printed output in a file

import sys f = open("outfile.txt", "w") old_sys_stdout = sys.stdout sys.stdout = f print("A first line.") sys.stdout = old_sys_stdout f.close() The resulting file contains the printed line. Saving the previous stream allows the program to restore output after redirection.

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains input conversion, stream methods, redirection and restoration, then points to specialized persistence and binary-format tools.
Examples
Demonstrates input(), integer conversion, sys.stdin.readline(), stdout redirection, print(file=f), and captured file contents.
What it assumes
Assumes general programming knowledge and treats input as text requiring explicit conversion for numeric use.
What you can do after
Apply Python’s input, stream, file, path, binary-format, and persistence interfaces to move or save program data.
How it connects
Connects file objects with standard input/output/error, pathlib, binary data, serialization, persistence, and cross-platform filesystem paths.

Also explained in

Compare how 4 books explain I/O →

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.