niyant
niyant

Reputation: 499

Python inbuilt fuction os.path.dirname(path) giving inconsistant output?

os.path.dirname("C:\\myfile\test.h")

gives result

'C:\\' as dir name

Whereas

os.path.diranme("C:\\myfile\mytest.h")

gives result

'C:\\myfile'

How to get 2nd output all the times ? Using python 2.7

Upvotes: 0

Views: 41

Answers (1)

Kevin
Kevin

Reputation: 76254

"C:\\myfile\test.h" is equivalent to "C:\\myfile[tab character]est.h". Its directory is "C:\\" and its file name is "myfile[tab character]est.h".

If you want the file with name "test.h" and directory "C:\\myfile", you should escape that backslash: "C:\\myfile\\test.h". Alternatively, use raw strings: r"C:\myfile\test.h". Alternatively, use "/" if your OS supports it: "C:/myfile/test.h"

"C:\\myfile\mytest.h" does not share this problem because \m is not a valid escape sequence, so Python interprets it as a backslash and an M.

Upvotes: 3

Related Questions