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?

2
  • Repeated question Please see stackoverflow.com/questions/8384737/… Commented Apr 6, 2016 at 16:28
  • @PrakharAgrawal this question about path stored as basic python string. Commented Apr 6, 2016 at 16:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Always use unicode to convert QString, so as to avoid encoding errors with non-ascii characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.