-1

Recently I had some trouble writing code in Ubuntu and make it work in Windows.

Code on both platforms:

enter image description here

Output Ubuntu (that's what I want):

enter image description here

Output Windows:

enter image description here

As you can see, split on windows adds a '/' instead of splitting the list by '/'. Is the list.split() not cross platform?

Artur Müller Romanov
  • 4,417
  • 10
  • 73
  • 132

3 Answers3

5

Use os.sep

Ex:

import os

importpath = __file__
print(importpath.split(os.sep))
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Kind of right, but that doesn't include the case where a path under windows is separated by a `/`, which is valid too. – glglgl Dec 17 '18 at 08:35
  • This works in my case. Thank you. Could you elaborate how `os.sep` works exactly? How does it recognize by which characters it has to seperate? – Artur Müller Romanov Dec 17 '18 at 08:37
  • 2
    Have a look at the documentation of [`os.sep`](https://docs.python.org/3/library/os.html#os.sep). – Matthias Dec 17 '18 at 08:41
  • 3
    Note that it also reads "Note that knowing this is not sufficient to be able to parse or concatenate pathnames — use `os.path.split()` and `os.path.join()` — but it is occasionally useful." – glglgl Dec 17 '18 at 08:42
2

A more "universal" way to do it is by using os.path.split(). This splits the path at the last separator. The first part must be treated iteratively or recursively.

Under Windows, think of splitting the drive letter as well.

Something like

drv, path = os.path.splitdrive(fullpath)
spl = []
while path:
    path, lastpart = os.path.split(path)
    spl.append(lastpart)
spl.append(drv) # as needed
spl.reverse()

should do it, but I don't have Windows at hand and cannot test it.

glglgl
  • 89,107
  • 13
  • 149
  • 217
1

If you want to be super safe, you should use repeatedly os.path.split, or test for both os.sep and os.altsep as separator.

__file__ will always use os.sep, but when you get a path from other code or by direct input from a user, chances are that os.altsep ('/' on Windows) is used.

Example on Windows:

>>> path = os.path.join('c:\\a', 'c/d')
>>> print(path)
'c:\\a\\c/d'
>>> pathsep = re.compile(r'\\|/')
>>> pathsep.split(path)
['c:', 'a', 'b', 'c']

Alternatively:

 def safe_split(path):
    res = []
    while True:
        path, tail = os.path.split(path)
        if len(tail) == 0:
            break
        res.append(tail)
    res.append(path)           # do not forget the initial segment
    res.reverse()
    return res

and

>>> safe_split('c:\\a\\c/d')
['c:\\', 'a', 'c', 'd']
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252