Python File Input and Output 5 — Questions and Answers
Question 1: What does json.dump(obj, fp) do versus json.dumps(obj)?
- dump() returns a string; dumps() writes to a file
- dump() writes to a file object; dumps() returns a string (Correct answer)
- They are identical in behavior
- dump() is for binary files; dumps() is for text files
Correct answer: dump() writes to a file object; dumps() returns a string
json.dump() serializes obj and writes directly to a file-like object fp, while json.dumps() returns the JSON string.
Question 2: Which flag in open() prevents Windows from translating '\n' to '\r\n' on write?
- mode='rb'
- newline='' (Correct answer)
- newline=None
- errors='ignore'
Correct answer: newline=''
Passing newline='' disables universal newline translation so Python writes exactly the characters you provide without CR+LF conversion.
Question 3: What does os.walk() yield for each directory it visits?
- A single Path object
- A tuple of (dirpath, dirnames, filenames) (Correct answer)
- A list of file paths only
- A dict with 'root', 'dirs', and 'files' keys
Correct answer: A tuple of (dirpath, dirnames, filenames)
os.walk() yields a 3-tuple (dirpath, dirnames, filenames) for each directory in the tree rooted at the given path.
Question 4: What is the effect of opening a file with mode 'w+' when the file already exists?
- It raises FileExistsError
- It opens for reading only
- It truncates the file to zero length then allows reading and writing (Correct answer)
- It appends new content and allows reading
Correct answer: It truncates the file to zero length then allows reading and writing
'w+' opens the file for reading and writing but first truncates it to zero bytes, destroying any prior content.
Question 5: How do you read exactly 10 bytes from a binary file?
- file.read(10) (Correct answer)
- file.readline(10)
- file.readbytes(10)
- file.fetch(10)
Correct answer: file.read(10)
file.read(size) reads and returns up to size bytes; in binary mode this returns a bytes object of at most 10 bytes.
Question 6: What does the pickle.dump() function require as its second argument?
- A filename string
- A writable binary file object (Correct answer)
- A writable text file object
- A dict of serialization options
Correct answer: A writable binary file object
pickle.dump(obj, file) requires a binary-mode file object opened for writing because pickle serializes data as bytes.
Question 7: Which pathlib method returns the suffix (extension) of a file path?
- Path.extension
- Path.suffix (Correct answer)
- Path.ext
- Path.name[-1]
Correct answer: Path.suffix
Path.suffix returns the file extension as a string including the dot, e.g. '.txt', or an empty string if there is no extension.
What does json.dump(obj, fp) do versus json.dumps(obj)?