2

How do I best identify if a String is a Windows path or a UNIX style path?

Example Strings:

some_path = '/Volumes/network-drive/file.txt'

or

some_path = 'Z:\\network-drive\\file.txt'

One way is to check which slashes the String contains:

if '/' in some_path:
   # do something with UNIX Style Path
elif '\\' in some_path:
   # do something else with Windows Path 

Is there a better way to do this? I couldn't find suited methods in os.path or pathlib.
BTW, assume that the path string will come from another system so it doesn't help to check on which OS my code runs on.

Tobias Mayr
  • 196
  • 4
  • 16
  • 1
    One potential wrinkle is that `"./Temp"` might be considered valid under either OS at least as far as things like `os.chdir("./Temp")` – JonSG Apr 20 '21 at 16:53
  • @JonSG that's correct, Windows doesn't care if you use a forward slash or a backward one. The only reason they standardized on the backward one is that early DOS programs often used the forward slash to indicate a command line option rather than the dash used by Unix. – Mark Ransom Apr 20 '21 at 17:21
  • If you have some control over the source of the filenames, you could choose some tokens to represent common base directories and use string replacement to create the final filename appropriate for the system in use. For example you could use `[NETWORK]/file.txt`. – Mark Ransom Apr 20 '21 at 17:26
  • I might ask the frontend dev to provide another field for the OS but I was hoping that this can be avoided and there is a reliable way to identify the path type in the backend. Good to know about this that the forward slash is already not an option. Additionally, file names in unix like systems(just tried with MacOS) seem to also accept backward slashes – Tobias Mayr Apr 20 '21 at 17:53
  • 1
    Does this answer your question? [Can python detect which OS is it running under?](https://stackoverflow.com/questions/4719063/can-python-detect-which-os-is-it-running-under). It does not use the file and directory names, but platform.uname. – Nic3500 Apr 24 '21 at 02:47
  • No @Nic3500, the os is always unix – Tobias Mayr Jun 04 '21 at 12:22

0 Answers0