pythonpathlib

Is pathlib.Path.read_text() better than _io.TextIOWrapper.read()?


I've recently discovered that pathlib offers some methods for dealing with file paths. When looking through the list of methods, .read_text() caught my attention. It implied that I could keep an object of type Path that stores a bunch of useful info in one neat package as well as offering the option of getting the file string without having to manually close/open a text file or using with open():.

I am about to change my default coding practices fundamentally unless I hear of a good reason why not to do it. So I wanted to know: is there a good reason why _io.TextIOWrapper.read() is better?


Solution

  • read_text() on pathlib-objects in CPython is just a shorthand for

        def read_text(self, encoding=None, errors=None, newline=None):
            """
            Open the file in text mode, read it, and close the file.
            """
            with self.open(mode='r', encoding=encoding, errors=errors, newline=newline) as f:
                return f.read()
    

    In other words, all those methods (open, TextIOWrapper, pathlib) work exactly the same. Use whatever is most convenient in your particular situation.