Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 699
yurisnm Avatar asked Feb 17 '26 21:02

yurisnm


1 Answers

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)
like image 96
snibbets Avatar answered Feb 20 '26 11:02

snibbets



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!