Reading files

To read the file back we use open() again, but this time we pass 'rt', for read-text, as the mode:

>>> g = open('wasteland.txt', mode='rt', encoding='utf-8')

If we know how many bytes to read, or if we want to read the whole file, we can use read(). Looking back through our REPL we can see that the first write was 32 characters long, so let's read that back with a call to the read() method:

>>> g.read(32)
'What are the roots that clutch, '

In text mode, the read() method accepts the number of characters to read from the file, not the number of bytes. The call returns the text and advances the file pointer to the end of what was read. Because we opened the file in text mode, the return type is str.

To read all the remaining data in the file we can call read() without an argument:

>>> g.read()
'what branches grow Out of this stony rubbish? '

This gives us parts of two lines in one string — note the newline character in the middle.

At the end of the file, further calls to read() return an empty string:

>>> g.read()
''

Normally when we have finished reading a file we would close() it. For the purposes of this exercise, though, we'll keep the file open and use seek() with an argument of zero to move the file pointer back to the start of the file:

>>> g.seek(0)
0

The return value of seek() is the new file pointer position.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset