Patternite Logo

Use pathlib to read the contents of a simple text file

3

A terse way to read the contents of a simple text file using the built-in pathlib module

Loading...

Commonly, we want to read in the contents of a simple text file, line-by-line, as a list of strings. The canonical approach is to create a file object (often denoted f) with open and then call a method such as readlines (shown on line #8 and #13). However, we can simplify this using the built-in pathlib module and its read_text method (shown on line #17).

Checkout the excellent pathlib module here.

Profile picture for JohnGiorgi

| edited

Profile picture for duncster

0

Nice! pathlib is a great module.

Patternite © 2021

Patternite Logo