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
Use the file-or-text exercise to practice checking whether input names a file before opening and reading it. section 5.1









