Why use `with open(...)` for file operations?
The `with` statement automatically closes the file when the indented block ends, even if an exception occurs.
Study 6 File Input and Output with 12 free online flashcards. Review key terms, definitions, and concepts with this interactive flashcard deck.
Why use `with open(...)` for file operations?
The `with` statement automatically closes the file when the indented block ends, even if an exception occurs.
What do the file modes `"r"`, `"w"`, and `"a"` do?
`"r"` reads an existing file, `"w"` creates or replaces a file, and `"a"` appends to its end.
What does a file object's `read()` method return?
`read()` returns the remaining file contents as one string.
How should a large text file usually be processed?
Iterating over the file object processes one line at a time and is generally the most memory-efficient pattern for large text files.
What does `write()` do, and what does it return?
`write()` writes one string and returns the number of characters written; it does not add a newline automatically.
When should a file be opened in binary mode?
Use binary mode such as `"rb"` or `"wb"` for bytes and non-text data such as images, audio, and compressed files.
How do relative and absolute file paths differ?
A relative path is interpreted from the program's current working directory; an absolute path specifies the complete location.
Why use `pathlib.Path` for file paths?
`pathlib.Path` constructs and inspects paths with platform-independent operations, avoiding manual path-separator handling.
Why explicitly specify UTF-8 for text files?
Specify `encoding="utf-8"` so characters are decoded consistently and behavior is less dependent on the computer's locale.
Why use `newline=""` when opening a CSV file?
Open CSV files with `newline=""` so Python's `csv` module can handle newline conventions correctly.
What do `Path.write_text()` and `Path.read_text()` do?
`write_text()` replaces an existing file with text, while `read_text()` opens, reads, and returns the decoded contents.
Which file-reading exceptions commonly need targeted handling?
Handle `FileNotFoundError` when the file is missing, `PermissionError` when access is denied, and `UnicodeDecodeError` when text is not valid UTF-8.