File Input and Output Flashcards
7 cards from real Python practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 7 File Input and Output flashcards as text
Which io class should you use to work with in-memory text streams?
Answer: io.StringIO
io.StringIO provides an in-memory stream for text, implementing the same interface as a regular text file.
What does pathlib.Path.write_text(data) do if the file already exists?
Answer: Overwrites the file with the new data
Path.write_text() opens the file in 'w' mode and overwrites any existing content with the provided text.
Which method of pathlib.Path lists all immediate children of a directory?
Answer: Path.iterdir()
Path.iterdir() yields Path objects for all entries (files and directories) directly inside the directory.
What does open(file, buffering=0) mean?
Answer: Disable buffering (only valid in binary mode)
Setting buffering=0 disables buffering; this is only permitted in binary mode and causes each read/write to go directly to the OS.
What does shutil.copy2(src, dst) preserve that shutil.copy(src, dst) does not?
Answer: File metadata (timestamps)
shutil.copy2() copies content and permissions like copy(), but also preserves the file's metadata such as modification timestamps.
When iterating over a file object line by line with 'for line in file:', what is included in each line?
Answer: The line with its trailing newline character
When iterating a file, each yielded string includes the trailing newline '\n', which you must strip manually if not needed.
What is the purpose of the errors parameter in open()?
Answer: Specifies how encoding/decoding errors are handled
The errors parameter (e.g., 'ignore', 'replace', 'strict') defines what happens when a character cannot be encoded or decoded.