dperrie dperrie - 12 days ago 8
Python Question

How to remove all characters before the final \

I have a variable called

dllName
that grabs the name of a dll that has been executed. Sometimes this dll is returned in the format of
"kernel32.dll"
and sometimes as
"C:\Windows\system32\kernel32.dll"
.

The path can vary, what I am trying to achieve is the stripping of the
"C:\Windows\system32\"
.

EDIT: Extract file name from path, no matter what the os/path format

My question is not the same as this question, as os.path.basename and os.path.split do not work in this situation.

For os.path.split the head is empty and the tail contains the whole path?

Answer

You could use :

path = 'C:\\Windows\\system32\\kernel32.dll'
print path.split('\\')[-1]
#=>  kernel32.dll

or

import os.path
print os.path.basename(path)

or

import re

def extract_basename(path):
  """Extracts basename of a given path. Should Work with any OS Path on any OS"""
  basename = re.search(r'[^\\/]+(?=[\\/]?$)', path)
  if basename:
    return basename.group(0)

print extract_basename(path)

This last example should work for any OS, any Path.

Here are some tests.