yurisnm
yurisnm

Reputation: 1640

Splitting a simple specific path on windows and linux

Problem:

I'm having different behavior for Windows and Linux in the following case.

import os
path = '..\\file.hdf'
norm_path = os.path.normpath(path)
splitted_path = os.path.split(norm_path)
print(splitted_path)

Behavior

On Windows I get ('', 'file.hdf')

On Linux I get ('', '..\\file.hdf')

Question

Is there a better/specific way to use the os.path for this?

Workaround

Ok, it's easily fixed with norm_path.split('\\'), but that's not dynamic at all.

Upvotes: 2

Views: 1510

Answers (3)

gelonida
gelonida

Reputation: 5640

replace \\ with /

Windows can handle / as path separator.

Linux can't handle \\

So use / for any code you want to be able to be running on Linux and Windows

Or do it the really clean way by using os.sep as @snibbets suggests.

In that case I'd use os.sep.join('..', 'file.hdf')

Upvotes: 1

snibbets
snibbets

Reputation: 1145

On Linux, paths are separated with a forward slash. If you want a platform-independent approach, I suggest using os.sep instead of backslash:

import os
path = '..' + os.sep + 'file.hdf'
norm_path = os.path.normpath(path)
split_path = os.path.split(norm_path)
print(split_path)

Upvotes: 6

Błotosmętek
Błotosmętek

Reputation: 12927

In Linux \ is NOT a path separator. Therefore, your ..\\file.hdf means "a file named file.hdf in the parent directory of the current directory" on Windows, but simply "a file named ..\file.hdf in current directory" on Linux. I suggest using pathlib module instead of os.path:

import pathlib
norm_path = pathlib.PureWindowsPath('..\\file.hdf')
split_path = list(norm_path.parts)
# ['..', 'file.hdf'] both on Linux and Windows

Upvotes: 1

Related Questions