Search code examples
pythonpython-3.xfilepathpathlib

Python pathlib.Path - how do I get just a platform independent file separator as a string?


I am creating a format string that is different based on class, that is used to generate a filename by a generic class method. I'm using the Python 3.4+ pathlib.Path module for object-oriented file I/O.

In building this string, the path separator is missing, and rather than just put the windows version in, I want to add a platform independent file separator.

I searched the pathlib docs, and answers here about this, but all the examples assume I'm building a Path object, not a string. The pathlib functions will add the correct separator in any string outputs, but those are actual paths - so it won't work.

Besides something hacky like writing a string and parsing it to figure out what the separator is, is there a way to directly get the current, correct file separator string?

Prefer an answer using pathlib.Path, rather than os or shutil packages.

Here's what the code looks like:

In the constructor:

    self.outputdir = Path('drive:\\dir\\file')
    self.indiv_fileformatstr = str(self.outputdir) + '{}_new.m'

In the final method used:

    indiv_filename = Path(self.indiv_fileformatstr.format(topic))

This leaves out the file separator


Solution

  • There is nothing public in the pathlib module providing the character used by the operating system to separate pathname components. If you really need it, import os and use os.sep.

    But you likely don't need it in the first place - it's missing the point of pathlib if you convert to strings in order to join a filename. In typical usage, the separator string itself isn't used for concatenating path components because pathlib overrides division operators (__truediv__ and __rtruediv__) for this purpose. Similarly, it's not needed for splitting due to methods such as Path.parts.

    Instead of:

    self.indiv_fileformatstr = str(self.outputdir) + '{}_new.m'
    

    You would usually do something like:

    self.indiv_fileformatpath = self.outputdir / '{}_new.m'
    self.indiv_fileformatstr = str(self.indiv_fileformatpath)