1

While making a wsgi app I am in need of joining route names like /apple, apple/buy etc.

    import os
    path = os.path.join("/apple/", "/buy")
    print("route path:", path)

Now the problem is it works fine in *nix systems but on dos ones the ouput could become:

    route path: apple\buy

cuz what is wanted was unix style paths like - apple/buy

is their a way that I can always get unix style paths? should I use something other than os module?

omar
  • 190
  • 1
  • 10
  • 1
    You only need the output to print/show some string? If that's the case, does `.replace("\\", "/")` after the path definition solve the problem? ([Based on this answer](https://stackoverflow.com/a/18776536/3281097)) – aaossa Feb 14 '22 at 00:10
  • @aaossa well looks all right but what would happen when someone does `os.path.join("this/", "/is/", "a url/").replace("\\, "/")` i guess it would still work. thanks for the tip – omar Feb 14 '22 at 00:18

2 Answers2

2

os.path is a alias to posixpath or ntpath. You can import one of those modules directly to get the path rules you want. So, import posixpath and use functions like posixpath.join.

>>> import os
>>> os.path.__name__
'posixpath'
>>> import posixpath
>>> posixpath.join is os.path.join
True
>>> 

You could

import os
import posixpath
os.path = posixpath

But that can be a bad choice because it would also affect any code that wants to work with local platform paths. Its usually best to use posixpath directly as needed.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • Additionally, you could import `posixpath.join` directly with an alias: `from posixpath import join as posixjoin` – aaossa Feb 14 '22 at 00:14
  • @tdelaney I guess posixpath is ideal for weburls then. I am not using it for local platform paths. infact I am intending to use it in a url router module. thanks for the help – omar Feb 14 '22 at 00:14
1

os.path is for path operations on the current operating system. Use urllib.parse.urljoin to join URL paths.

Richard Neumann
  • 2,986
  • 2
  • 25
  • 50