Python File Input and Output 4 — Questions and Answers
Question 1: Which io class should you use to work with in-memory text streams?
- io.BytesIO
- io.StringIO (Correct answer)
- io.FileIO
- io.BufferedReader
Correct answer: io.StringIO
io.StringIO provides an in-memory stream for text, implementing the same interface as a regular text file.
Question 2: What does pathlib.Path.write_text(data) do if the file already exists?
- Appends to the existing content
- Raises FileExistsError
- Overwrites the file with the new data (Correct answer)
- Returns False without writing
Correct 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.
Question 3: Which method of pathlib.Path lists all immediate children of a directory?
- Path.list()
- Path.iterdir() (Correct answer)
- Path.children()
- Path.glob('*/')
Correct answer: Path.iterdir()
Path.iterdir() yields Path objects for all entries (files and directories) directly inside the directory.
Question 4: What does open(file, buffering=0) mean?
- Use the default buffer size
- Use a 1-byte buffer
- Disable buffering (only valid in binary mode) (Correct answer)
- Use an unlimited buffer
Correct 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.
Question 5: What does shutil.copy2(src, dst) preserve that shutil.copy(src, dst) does not?
- File permissions
- File content
- File metadata (timestamps) (Correct answer)
- File ownership
Correct answer: File metadata (timestamps)
shutil.copy2() copies content and permissions like copy(), but also preserves the file's metadata such as modification timestamps.
Question 6: When iterating over a file object line by line with 'for line in file:', what is included in each line?
- The line without any newline character
- The line with its trailing newline character (Correct answer)
- The line number followed by the text
- Only the stripped whitespace-free content
Correct 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.
Question 7: What is the purpose of the errors parameter in open()?
- Sets the maximum number of read errors allowed
- Specifies how encoding/decoding errors are handled (Correct answer)
- Enables logging of I/O errors to stderr
- Controls whether OSError is raised on write failure
Correct 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.
Which io class should you use to work with in-memory text streams?