Chapter Review Questions#
The
withstatement andopen().What does the
withstatement do when used withopen()?Why is this preferable to calling
f.close()manually?
What mode string do you pass to
open()to write to a file? What happens if the file already exists?What mode string do you pass to
open()to append to an existing file?Iterating over lines.
In a
for line in f:loop, does eachlinestring include the trailing newline character?How do you remove it?
Two ways to read a file.
What does
f.read()return?What does
f.readlines()return?When would you prefer each?
Write a cross-platform path for the file
data.txtlocated in a subdirectory calledinputof the current directory, usingpathlib.Path.What does
..mean in a relative path?In the path
Path("a") / "b" / "c.txt", what is returned by:.name.stem.suffix.parent
What method checks whether a path points to an existing file?
What is logically wrong with the following code?:
with open("data.txt") as f: first = f.readline() if "error" in f.readline(): print("Error on line:", f.readline())