A Python file object is the handle used to read from or write to an opened file. `open()` takes a pathname and returns the object; it does not read the file. The object keeps track of how much has been read or written. section 13.1
Write, then read
`with open('myfile', 'w') as file_object: file_object.write('First line\n') with open('myfile', 'r') as file_object: line = file_object.readline()` The first block writes a line in `w` mode. The second opens the file in `r` mode; `readline()` returns the line including its newline character. `with` closes each file when its block ends. section 3.2.7 section 13.1 section 13.2
Keep the file and its pathname distinct:
- A relative pathname such as `myfile` refers to a file in the current working directory. `os.path.join()` can assemble path components according to the operating system’s conventions. section 3.2.7 section 13.1
- Close a file object when finished. `close()` does this explicitly; `with` does it automatically, including when an exception occurs. Leaving many files open can exhaust system resources. section 13.2 section 14.5
- Choose the I/O approach to fit the data. Text is the default, while binary mode processes bytes. For a file too large to manipulate in memory, process smaller segments, potentially one line at a time. section 13.11 section 21.2
File objects are the I/O side of working with data files; naming, moving, and managing those files are separate filesystem tasks. Data may arrive as plain text, delimited records, or many accumulated files, so opening one file is often only the first step in processing it. section 12.0 section 21.0 section 20.1







