Pathlib - switching path from Windows to Mac

Hello all,

I’m trying to make a script more generic so it can be run on a Mac while created on a windows (I know I could just change the path manually but I would like a better option).
To do so I’m using the pathlib command but running into issues.

Here is what I have done so far in the coder. in italics are the output from each line:

home = str(Path.home())

***  '/Users/myname' ***

conditionmixer_folder = PureWindowsPath(“\Box\Folder\SubStudy3\conditionmixer\”)

***  PureWindowsPath('/Box/Folder/SubStudy3/conditionmixer') ***

path_on_mac = Path(conditionmixer_folder)


and then I try generating a path to make it work on the Mac (that includes other options):
listvariable.append({“condfile”:home + str(path_on_mac) + hehe.get(“condfile”)})
it does not work because cannot find the file:

ValueError: Conditions file not found: /Users/beynellc/Box/Folder/SubStudy3_Neurofeedback/conditionmixercond3animal.xlsx

I noticed that there is a backward and forward slashes joining home and the path.
when I looked at the output of str(path_on_mac) I’m getting


and there is still \/ do you know how I can get rid of that?

Thank you !

I run into this all the time, as much as I love Pathlib it’s very annoying. I think this is because PosixPath interprets a path beginning with “/” as being relative to the root folder (“\”) while WindowsPath interprets it as being a relative path. Does it fix the problem if you add a “.” to the beginning of your path when defining the original object?

Thank you for your answer. At least I’m glad I’m not the only one having this issue

Adding the “.” helps a bit cause it switches from:


However when I use the home + str(path_on_mac) to append it, it fully remove the slash


Any other options ?

Oh I figured it out,

I added a + “/” after calling home and that fixed it!

Thank you !!

1 Like

I think you can also do

home / path_on_mac

and Pathlib should handle this