pathlib Path `write_text` in append mode
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("...")
The pathlib
methods Path().write_text()
and Path().write_bytes()
close the file connection on exit.
from pathlib import Path
Path('file.txt').write_text('my text')
Path('file1.txt').write_bytes(b'my text')
Using append mode i.e open('a', ...)
will instanciate a TextIOWrapper
which is also closed by write_text
/ write_bytes
on exit.
f = Path('file.txt')
f.open("a")
f.write_text('my text')
# or
f.write_bytes(b'my text')
Otherwise must close it manually
f = Path('file1.txt').open('a')
f.write('my text')
f.close()
but can be this way:
fp = Path('test.txt').open('a')
<_io.TextIOWrapper name='test.txt' mode='a' encoding='UTF-8'>
fp.write('my text')
fq = Path('test1.txt').open('ab', encoding='iso8859-1')
<_io.TextIOWrapper name='test1.txt' mode='a' encoding='iso8859-1'>
fq.write(b'my text')