1

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.

5
  • 1
    "\\" is actually a single character, so it is no different from any of the other slashes in your string. Commented Oct 29, 2015 at 16:08
  • 1
    os.path.basename(text2)? Commented Oct 29, 2015 at 16:09
  • I have changed the question a little bit . Now I am saving the file in path as 'C:\Users\Sony\Desktop\f.html' Commented Oct 29, 2015 at 16:26
  • Rogalski's comment is probably the best approach. Commented Oct 29, 2015 at 16:26
  • Yeah os.path.dirname(text2) Thanks Rogalski :) and Kevin and Celeo Commented Oct 29, 2015 at 16:29

1 Answer 1

3

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'
Sign up to request clarification or add additional context in comments.

2 Comments

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 ?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.