1

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?

dperrie
  • 315
  • 1
  • 2
  • 11
  • 1
    No regex required, just use [`os.path.basename`](https://docs.python.org/2.7/library/os.path.html#os.path.basename) – Aran-Fey Nov 28 '16 at 12:25
  • Can you show us what you have tried that doesn't work or that you have difficulties with? If you haven't tried any code yourself yet, you could use the search functionality on stackoverflow maybe? – Oliver W. Nov 28 '16 at 12:26
  • @Rawing: `os.path.basename` won't work for Windows path on Linux. – Eric Duminil Nov 28 '16 at 12:55

1 Answers1

1

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.

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124