Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split path with slashes?

Tags:

python

I have a requirement for adding and splitting path in my app.I want to work with this app on windows and linux.Here is my code to add paths

 path = os.path.join(dir0,dir1,dir2,fn)

But when i am splitting with slashes i am facing problems .Because

the path in windows like:

dir0\dir1\dir2\fn

the path in linux like

dir0/dir1/dir2/fn

Now how can i split the path with single code(with out changing the code while using other platform/platform independent)

like image 398
Shiva Avatar asked Dec 02 '22 20:12

Shiva


2 Answers

You can use os.sep

just

import os
path_string.split(os.sep)

For more info, look the doc

os.path.join(path1[, path2[, ...]]) Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return value is the concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) following each non-empty part except the last. (This means that an empty last part will result in a path that ends with a separator.) Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

like image 141
atupal Avatar answered Dec 05 '22 10:12

atupal


Use os.path.split. It is a system independent way to split paths. Note that this only splits into (head, tail). To get all the individual parts, you need to recursively split head or use str.split using os.path.sep as the separator.

like image 31
Jayanth Koushik Avatar answered Dec 05 '22 10:12

Jayanth Koushik