2

This Question Already have a solution but In my case I'm not getting the correct solution where am I getting wrong?

import os,sys filename = "C:\Users\Dell\Desktop\ProjectShadow\app2\aapp2s.py" directory, module_name = os.path.split(filename) module_name = os.path.splitext(module_name)[0] print(module_name) print(directory) 

I get following Result

Insterd I want

>> aapp2s C:\User\Dell\Desktop 

What's Wrong ?

2
  • 3
    you're missing the raw prefix r"C:\users\.... \a is a special escape sequence. Commented Jan 19, 2017 at 13:46
  • 1
    Backslashes in string literals should be escaped. e.g. "C:\\Users\\Dell\\Desktop\\ProjectShadow\\app2\\aapp2s.py", or use r prefix, e.g. r"C:\Users\Dell\Desktop\ProjectShadow\app2\aapp2s.py" Commented Jan 19, 2017 at 13:47

2 Answers 2

2

either use r"C:\Users\Dell\Desktop\ProjectShadow\app2\aapp2s.py" or you can double backshlash the whole thing "C:\\Users\\Dell\\Desktop\\ProjectShadow\\app2\\aapp2s.py"

The strange thing you see on your print is the result of the \a escape char

Sign up to request clarification or add additional context in comments.

2 Comments

what if link is stored in a variable ? how do i use regular expression r' ? with variable??
@amitnair92 well you can use something like newText = "%r"%textFromVariable
0

Try pathlib:

from pathlib import PureWindowsPath filename = r"C:\Users\Dell\Desktop\ProjectShadow\app2\aapp2s.py" p = PureWindowsPath(filename) module_name = p.stem directory = p.parents[2] print(module_name) print(directory) 

out:

aapp2s C:\Users\Dell\Desktop 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.