Appending to files

Sometimes we would like to append to an existing file, and we can do that by using the mode 'a'. In with this mode, the file is opened for writing and the file pointer is moved to the end of any existing data. In this example we combine 'a' with 't' to be explicit about using text mode:

>>> h = open('wasteland.txt', mode='at', encoding='utf-8')

Although there is no writeline() method in Python, there is a writelines() method which writes an iterable series of strings to the stream. If you want line endings on your strings you must provide them yourself. This may seem odd at first, but it preserves symmetry with readlines() whilst also giving us the flexibility for using writelines() to write any iterable series of strings to a file:

>>> h.writelines(
... ['Son of man, ',
... 'You cannot say, or guess, ',
... 'for you know only, ',
... 'A heap of broken images, ',
... 'where the sun beats '])
>>> h.close()

Notice that only three lines are completed here — we say completed because the file we're appending to did not itself end with a newline.

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

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