mutapath.Path.in_place
- Path.in_place(mode='r', buffering=-1, encoding=None, errors=None, newline=None, backup_extension=None)[source]
A context in which a file may be re-written in-place with new content.
Yields a tuple of
(readable, writable)
file objects, where writable replaces readable.If an exception occurs, the old file is restored, removing the written data.
Mode must not use
'w'
,'a'
, or'+'
; only read-only-modes are allowed. AValueError
is raised on invalid modes.For example, to add line numbers to a file:
p = Path(filename) assert p.isfile() with p.in_place() as (reader, writer): for number, line in enumerate(reader, 1): writer.write('{0:3}: '.format(number))) writer.write(line)
Thereafter, the file at filename will have line numbers in it.