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
What does json.dump(obj, fp) do versus json.dumps(obj)?
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.
Which flag in open() prevents Windows from translating '\n' to '\r\n' on write?
Answer: newline=''
Passing newline='' disables universal newline translation so Python writes exactly the characters you provide without CR+LF conversion.
What does os.walk() yield for each directory it visits?
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.
What is the effect of opening a file with mode 'w+' when the file already exists?
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.
How do you read exactly 10 bytes from a binary file?
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.
What does the pickle.dump() function require as its second argument?
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.
Which pathlib method returns the suffix (extension) of a file path?
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.