Python File Input and Output 3 — Questions and Answers
Question 1: What does file.seek(0) accomplish?
- Closes the file
- Moves the file pointer to the beginning (Correct answer)
- Reads the first byte
- Truncates the file to zero bytes
Correct answer: Moves the file pointer to the beginning
file.seek(0) moves the read/write position back to byte offset 0, which is the start of the file.
Question 2: What is the third argument to file.seek(offset, whence)?
- The encoding to use
- The reference position: 0=start, 1=current, 2=end (Correct answer)
- The number of bytes to skip
- The buffer size
Correct answer: The reference position: 0=start, 1=current, 2=end
The whence argument specifies the reference point: 0 for start of file, 1 for current position, and 2 for end of file.
Question 3: Which module provides the NamedTemporaryFile context manager?
- os
- io
- tempfile (Correct answer)
- shutil
Correct answer: tempfile
The tempfile module provides NamedTemporaryFile, TemporaryFile, and other utilities for creating temporary files.
Question 4: What does file.truncate(n) do?
- Reads n bytes from the file
- Resizes the file to at most n bytes (Correct answer)
- Moves the pointer to position n
- Deletes the first n lines
Correct answer: Resizes the file to at most n bytes
file.truncate(size) resizes the file to at most size bytes; if size is omitted, the current position is used.
Question 5: In Python, which exception is raised when a file is not found?
- IOError
- FileNotFoundError (Correct answer)
- OSError
- MissingFileError
Correct answer: FileNotFoundError
FileNotFoundError is raised when a file or directory is requested but cannot be found; it is a subclass of OSError.
Question 6: What does the with statement guarantee when used with open()?
- The file is opened in binary mode
- The file is closed automatically when the block exits (Correct answer)
- The file is read into memory entirely
- No exceptions can occur inside the block
Correct answer: The file is closed automatically when the block exits
The with statement invokes the file object's __exit__ method, which closes the file even if an exception is raised.
Question 7: What does csv.DictReader return for each row?
- A list of strings
- An OrderedDict (or dict in 3.8+) mapping header names to values (Correct answer)
- A tuple of values
- A CSV row object with attributes
Correct answer: An OrderedDict (or dict in 3.8+) mapping header names to values
csv.DictReader yields each row as a dict where keys come from the first-row headers and values are the row's fields.
What does file.seek(0) accomplish?