0Pricing
Python Academy · Lesson

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

  1. The Path Object
  2. Reading and Writing Files
  3. Globbing and Iterating
  4. Path Manipulation
← Back to Python Academy