pathlib Path `write_text` in append mode

danodonovan picture danodonovan · Jul 31, 2019 · Viewed 7.1k times · Source

Is there a shortcut for python pathlib.Path objects to write_text() in append mode?

The standard open() function has mode="a" to open a file for writing and appending to the file if that file exists, and a Paths .open() function seems to have the same functionality (my_path.open("a")).

But what about the handy .write_text('..') shortcut, is there a way to use pathlib to open and append to a file with just doing the same things as with open()?

For clarity, I can do

with my_path.open('a') as fp:
    fp.write('my text')

but is there another way?

my_path.write_text('my text', mode='a')

Answer

BPL picture BPL · Aug 4, 2019

Not really, as you can see in the pathlib module exist 2 types of path classes:

  • pure path classes {PurePath, PurePosixPath, PureWindowsPath}
  • concrete path classes {Path, PosixPath, WindowsPath}.

Parameters of theses classes constructors will be just *pathsegments.

And if you look at the available read/write methods (read_text/read_bytes and write_text/write_bytes) you'll also see mode won't be available neither

So, as you've already discovered, the only way you can use mode with these pathlib classes is by using open method, ie:

with my_path.open("a") as f:
    f.write("...")

This is by design and that way the pathlib classes have become really "clean". Also, the above snippet is already canonical so it can't be simplified any further. You could use open method outside the context manager though:

f = my_path.open("a")
f.write("...")