1

Python 3.4 (and above) has a module called pathlib which is for representing and working with paths. So, an instance of the pathlib class is an object which represents a path on the system (e.g. /home/my_file.py). I can use it to read a files contents, write to a file, etc... A file object is a, not surprisingly, an object which represents a file. I can use it to read a files contents, write to a file, etc...

So, what is the difference between the two objects? Why choose one over the other? Obviously, a file object isn't used to make copies or check the current working directory so there are reasons to choose pathlib when we need cerain behaviours. However, it seems pathlib does everything I might want a file object to do so why bother with file objects?

RhythmInk
  • 513
  • 1
  • 4
  • 18
  • `os.path `is a module for dealing with pathnames, which can be used to create `file` objects, typically via `open()`. `pathlib` is an object-oriented module for representing filesystem paths, manipulating, and _using_ them. Since it's the later, more modern, module and the `Path` objects it defines have a number of features that `file` objects also do. If it has everything you need, there's no reason to use `os.path` and separately create `file` objects — unless you need to support Python < 3.4. – martineau Dec 01 '19 at 09:11
  • @martineau you should write that up as an answer. Seems complete to me. – user1558604 Dec 01 '19 at 23:50
  • @user1558604: It's a comment because, especially the last part about whether to use `pathlib` exclusively is just because it simplifies things. However, to be honest, from an object-oriented-design point of view, I'm not totally on-board with the fact that `Path`s have had this extra functionality tacked on to them because it seems like it violates the [Single Responsibility Principle](https://www.oodesign.com/single-responsibility-principle.html), – martineau Dec 02 '19 at 01:43

0 Answers0