u936293
u936293

Reputation: 16264

Is os.path.basename meant for file system files?

In Windows, os.path.basename('D:\\abc\def.txt') returns abc\def.txt, whereas os.path.basename('/abc/def.txt') returns def.txt.

Shouldn't the first also return def.txt?

Upvotes: 1

Views: 1247

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123420

You have an escape code in your filename, not a \ directory separator. You must've simplified your problem by using def for the filename, but had you actually tested with that simplified filename you'd have noticed that the slash would be doubled:

>>> 'D:\\abc\def.txt'
'D:\\abc\\def.txt'

Note that the \d in the string literal became a \\ escaped backslash in the Python representation of the value. That's because there is no valid \d escape sequence. On a Windows system the os.path.basename() call works as expected for that path:

>>> import os.path
>>> os.path.basename('D:\\abc\\def.txt')
'def.txt'

In your case, however, you created an escape sequence, either \n, \r or \t, because you either forgot to double the backslash or you forgot to use a raw string. You do not have a \ character in that part of the filename, so there is nothing to split on at that location.

Use a r'...' raw string to prevent single backslashes from forming escape sequences, or double your backslashes in all locations, or use forward slashes (Windows accepts either).

Upvotes: 2

Related Questions