Writing to files

We've shown previously how we can request help() for modules and methods and types, but in fact we can request help on instances too. This makes sense when you remember that everything is an object.

>>> help(f)
. . .
| write(self, text, /)
| Write string to stream.
| Returns the number of characters written (which is always
| equal to
the length of the string).
. . .

Browsing through the help, we can see that f supports a method write(). Quit the help with q and continue at the REPL.

Now let's write some text to our file using the write() method:

>>> f.write('What are the roots that clutch, ')
32

The call to write() returns the number of codepoints or characters written to the file. Let's add a few more lines:

>>> f.write('what branches grow
')
19
>>> f.write('Out of this stony rubbish? ')
27

You'll notice that we're explicitly including newlines in the text we write to the file. It's the callers responsibility to provide newline characters where they are needed; Python does not provide a writeline() method.

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

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