Reputation: 21602
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?
Upvotes: 1
Views: 1000
Reputation: 15545
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.
Upvotes: 1