user177800
user177800

Reputation:

Dealing with BACKSLASH character in non-string literals in Python

I have the following string read from an XML elememnt, and it is assigned to a variable called filename. I don't know how to make this any clearer as saying filename = the following string, without leading someone to think that I have a string literal then.

\\server\data\uploads\0224.1307.Varallo.mov

when I try and pass this to

os.path.basename(filename)

I get the following

\\server\\data\\uploads\x124.1307.Varallo.mov

I tried filename.replace('\\','\\\\') but that doesn't work either. os.path.basename(filename) then returns the following.

\\\\server\\data\\uploads\\0224.1307.Varallo.mov

Notice that the \0 is now not being converted to \x but now it doesn't process the string at all.

what can I do to my filename variable to get this String in a proper state so that os.path.basename() will actually give me back the basename. I am on OSX so the uncpath stuff is not available.

All attempts to replace the \ with \\ manually fail because of the \0 getting converted to \x in the beginning of the basename.

NOTE: this is NOT a string literal so r'' doesn't work.

Upvotes: 0

Views: 655

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798546

All the downvoting in the world won't change the fact that you're doing it wrong. os.path is for native paths. \\foo\bar\baz is not a OS X path, it's a Windows UNC. posixpath is not equipped to handle UNCs; ntpath is.

Upvotes: 1

nosklo
nosklo

Reputation: 222842

We need more information. What exactly is in the variable filename? To answer, use print repr(filename) and add the results to your question above.


Wild guess

DISCLAIMER: This is a guess - try:

import ntpath
print ntpath.basename(filename)

Upvotes: 2

Related Questions