What is the general form of Python’s open() function?
The general form is open(file, mode="r", encoding=None). It returns a file object for reading or writing according to the selected mode.
Study 7 File Input and Output with 12 free online flashcards. Review key terms, definitions, and concepts with this interactive flashcard deck.
What is the general form of Python’s open() function?
The general form is open(file, mode="r", encoding=None). It returns a file object for reading or writing according to the selected mode.
What does file mode "r" do?
Mode "r" reads an existing file and is the default mode for open().
What does file mode "w" do?
Mode "w" writes to a file, replacing its existing contents. It creates the file if necessary.
What does file mode "a" do?
Mode "a" writes at the end of an existing file and preserves its contents. It creates the file if necessary.
When should mode "x" be used?
Mode "x" creates a new file and fails if a file with that name already exists.
What does adding "b" to a file mode mean?
Appending "b" selects binary mode, such as "rb" or "wb". Text modes handle str, while binary modes handle bytes.
Why explicitly specify UTF-8 when opening text files?
Specify encoding="utf-8" for predictable text processing across computers. Without it, Python may use a platform-dependent default.
How does file.read() behave?
read() returns the remaining file contents as one string. A size argument limits how much it reads, and later calls continue from the current position.
Why iterate over a file instead of calling read()?
Iterating over a file processes it one line at a time without loading the entire file into memory, making it suitable for large text files.
What does file.write() return, and what does it omit?
write() writes a string and returns the number of characters written. It does not add a newline automatically, so include "\n" when needed.
Why use / with pathlib.Path objects?
The / operator joins path components using the operating system’s appropriate conventions, making pathlib paths portable.
Why use a with statement for files?
A with statement closes the file automatically when execution leaves the block, even if an exception occurs. This safely releases the resource and flushes buffered output.