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.



