1

How to separate filename from path using Python?

I'm using PyQt4 and my String is not Python String but, PyQt4.QtCore.QString

I can do it like:

filename=my_path.split("/")[-1]

But I think separator is OS specific, also I can't use something like os.path.basename because it only work for original python string, so what will be the best option to do it?

Benny
  • 2,233
  • 1
  • 22
  • 27
mrgloom
  • 20,061
  • 36
  • 171
  • 301

1 Answers1

1

You can convert the QString to a Python str before use. For example:

filename_str = unicode(my_path)

...and then use standard Python os functions to get the filename:

os.path.basename(filename_str)

Or, in a single step:

os.path.basename(unicode(my_path))

Note you can avoid this problem altogether by using the newer PyQt4 API v2, or alternatively using PyQt5. With these updates PyQt functions return native Python strings (and other variables) where possible so you can work with them without converting. It makes things a lot simpler.

Community
  • 1
  • 1
mfitzp
  • 15,275
  • 7
  • 50
  • 70
  • 1
    Always use `unicode` to convert `QString`, so as to avoid encoding errors with non-ascii characters. – ekhumoro Apr 06 '16 at 17:23