Suppose I have a string , text2='C:\Users\Sony\Desktop\f.html', and I want to separate "C:\Users\Sony\Desktop" and "f.html" and store them in different variables then what should I do ? I tried out regular expressions but I wasn't successful.
1 Answer
os.path.split does what you want:
>>> import os
>>> help(os.path.split)
Help on function split in module ntpath:
split(p)
Split a pathname.
Return tuple (head, tail) where tail is everything after the final slash.
Either part may be empty.
>>> os.path.split(r'c:\users\sony\desktop\f.html')
('c:\\users\\sony\\desktop', 'f.html')
>>> path,filename = os.path.split(r'c:\users\sony\desktop\f.html')
>>> path
'c:\\users\\sony\\desktop'
>>> filename
'f.html'
2 Comments
Kanika Singh
Suppose p='c:\users\sony\desktop\f.html' , now when I write os.path.split(r p), then it gives me error, how to write this syntax when path is saved in a variable ?
Mark Tolonen
r is only used for literal string constants to suppress requiring escaping backslashes. It stands for "raw string". Just call os.path.split(p). I could have typed os.path.split('c:\\users\\sony\\desktop\\f.html') instead.
os.path.basename(text2)?