Reading and Writing Files
Use read_text and write_text.
File I/O the pathlib Way
pathlib paths can read and write files directly, without an explicit open() for simple cases. The methods read_text, write_text, read_bytes, and write_bytes cover the common needs.
write_text
write_text() writes a string to the file, creating it if needed and replacing any existing contents. It returns the number of characters written.
from pathlib import Path
p = Path('greeting.txt')
n = p.write_text('Hello, pathlib!')
print('wrote', n, 'characters')All lessons in this course
- The Path Object
- Reading and Writing Files
- Globbing and Iterating
- Path Manipulation