10.8. Pathlib Content

  • Path.read_text() - Read the content of a file as text

  • Path.write_text(data) - Write text data to a file

  • Path.read_bytes() - Read the content of a file as bytes

  • Path.write_bytes(data) - Write bytes data to a file

10.8.1. SetUp

>>> from pathlib import Path
>>>
>>> myfile = Path('/tmp/myfile.txt')

10.8.2. Write Text

  • Path.write_text() - Write text to the file

  • text: str - Text to write

  • encoding='utf-8'

  • Returns number of characters written

>>> myfile.write_text('Hello World')
11
>>> myfile.write_text('Hello World', encoding='utf-8')
11

10.8.3. Read Text

  • Path.read_text() - Read the entire file as text

  • encoding='utf-8'

>>> result = myfile.read_text()
>>> result
'Hello World'
>>> result = myfile.read_text(encoding='utf-8')
>>> result
'Hello World'