-1

I want to parse to var and set what i parse to a variable I want to parse C:\\level1\\level2\\level3\\level4\\level5\\level6\\level7\\level8 and make it intolevel7\level8` currently i am able to get level7 only

var = "C:\\level1\\level2\\level3\\level4\\level5\\level6\\level7\\level8"

split_path = os.path.split(os.path.split(var)[0])

print split_path

output below

('C:\\level1\\level2\\level3\\level4\\level5\\level6', 'level7')
Testerflorida
  • 99
  • 1
  • 1
  • 8

2 Answers2

0

The reason you only get 'level7' is because 'level8' is in

os.path.split(var)[1]

This should demonstrate it clearly:

var = "C:\\level1\\level2\\level3\\level4\\level5\\level6\\level7\\level8"
split_path = os.path.split(var)
level8 = split_path[1]
split_path = os.path.split(split_path[0])
level7 = split_path[1]
my_split_path = (split_path[0], os.path.join(level7, level8)

Here's the whole thing in one line:

my_split_path = (os.path.split(os.path.split(var)[0])[0], os.path.split(os.path.join(os.path.split(var)[0][1], os.path.split(var)[1])))

I'd recommend using multiple lines for clarity though.

As far as the double backslashes, Python string literals treat the first backslash as an escape character. So having two of them is effectively having one of them for all uses. In the interpreter var will output the string as you have it above, but print(var) will print single backslashes. This question has been answered in detail here: Why can't Python's raw string literals end with a single backslash?

Community
  • 1
  • 1
ShawSa
  • 154
  • 5
-1
>>> var = "C:\\level1\\level2\\level3\\level4\\level5\\level6\\level7\\level8"
>>> var.split('\\', 7)
['C:', 'level1', 'level2', 'level3', 'level4', 'level5', 'level6', 'level7\\level8']
>>> var.split('\\', 7)[-1]
'level7\\level8'

I don't get the same output as you with your code. It could be because I'm on OSX and that isn't recognized as a file path. Regardless, this solution is a bit simpler and gives you the bit you want.

The second parameter tells split the max number of times to split counting from left, so:

>>> var.split('\\', 1)
['C:', 'level1\\level2\\level3\\level4\\level5\\level6\\level7\\level8']
>>> var.split('\\', 2)
['C:', 'level1', 'level2\\level3\\level4\\level5\\level6\\level7\\level8']
# and so on...

You don't need to do anything to remove the extra '\', it's there to escape the one you want. You can see this by using print():

>>> print(var.split('\\', 7)[-1])
level7\level8
kylieCatt
  • 10,672
  • 5
  • 43
  • 51