14.1 Reading from files
1.
c.
The file is opened and is associated with the fileobj object. Reading from the file will be possible using fileobj.
3.
b.
Python interprets this command as the programmer trying to print the object details. The object details are printed. Ex:
<_io.TextIOWrapper name='newfile.txt' mode='r' encoding='cp1252'>
.
5.
b.
The
readlines()
function is called on fileobj
. file_lines
is the string list ['Hello world!\n', 'How are you?\n']
.
6.
a.
The
readline()
function reads the next line of a file. Since readline()
is called right after opening the file the first line is read. The resulting string
"Hello world!"
is printed. Note that readline()
includes the
'\n'
character so the print will include an additional newline.
14.2 Writing to files
3.
b.
'w'
indicates write mode, and newlog.txt will be created or overwritten (if newlog.txt already exists) and will allow writing.
4.
c.
resources.txt is likely empty, but the state of resources.txt is uncertain. To ensure the contents are saved correctly, the
close()
function must be used.
5.
a.
Write mode will overwrite the existing file. The
close()
statement finalizes changes to the file.
6.
b.
Append mode adds to the existing file. resources.txt is opened such that additions can be made to the file.
14.3 Files in different locations and working with CSV files
1.
b.
The path followed by the filename enables the file to be opened correctly and in read mode by default.
2.
c.
The use of forward slashes / replacing the Windows standard backslashes \ enables the path to be read correctly. The path followed by the filename enables the file to be opened and when reading a file read mode is preferable.
4.
a.
Since the backslashes in the Windows path appear in the string argument, which usually tells Python that this is part of an escape sequence, the backslashes must be ignored using an additional backslash \ character.
5.
a.
The newline
\n
character indicates where line breaks are in a file and is used by the readlines()
function to tell lines apart.
7.
c.
The first line of the books.csv is read into
csv_read
. The first line is
'Title, Author, Pages'
, which is the same as the first row.