dperrie dperrie - 1 year ago 74
Python Question

How to remove all characters before the final \

I have a variable called

that grabs the name of a dll that has been executed. Sometimes this dll is returned in the format of
and sometimes as

The path can vary, what I am trying to achieve is the stripping of the

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 Source

You could use :

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


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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download