I was recently converting a bash script to python. I had a need to grab the last item (and only the last item) off the end of a list in order to implement bash’s basename
function since Python’s basename function is not quite the same. The bash script had a line like the following
tmpbase=`basename $0`
I was able to get the information I needed by using the __file__
attribute in the script itself. From this, I was able to split the full pathname like this:
solj@abbysplaything $ cat foo.py #!/usr/bin/env python3 print(__file__.split('/')) solj@abbysplaything $ python /home/solj/foo.py ['', 'home', 'solj', 'foo.py']
As you can tell, the length of this path could vary depending on where the user runs the script from. Therefore, I needed to grab the first item from the end of the list in order to properly emulate the basename function of bash. I ended up being able to do the following:
tmpbase = __file__.split('/')[-1:]
The negative index allows you to count from the end of the list (I love Python). However, as it turns out, I am blind and didn’t finish fully reading the os.path documentation. This particular problem was solved in a much more elegant way using os.path.split() although I find the negative index to be an extremely useful thing to know.