[Tutor] Another way to strip?

Steven D'Aprano steve at pearwood.info
Thu Jan 19 19:53:09 EST 2017


On Thu, Jan 19, 2017 at 04:29:16PM -0500, ad^2 wrote:
> Hello all,
> 
> I'm looking for a cleaner more elegant way to achieve stripping out a file
> name from a list which contains a path and file extension.
> 
> Ex.
> 
> my_list = ['/var/tmp/02_80_5306_4444_2017_01_19_08-36-57_4918_0.zip',
> '/var/tmp/02_80_5309_4444_2017_01_19_08-40-30_4205_0.zip',
[...]
> '/var/tmp/02_80_5307_4444_2017_01_19_08-38-09_1763_0.zip']
> 
> >>> for i in my_list:
> ...     i.strip('/var/tmp/.zip')

That doesn't do what you think it does! That strips off each individual 
character '/', 'v', 'a', 'r', ... 'i', 'p' from the front and back of 
the string. If the format of the name changes, this could be 
disasterous:

py> path = '/var/tmp/tz-19_08-40-30_4205-a.zip'
py> path.strip('/var/tmp/.zip')  # expecting tz-19_08-40-30_4205-a
'-19_08-40-30_4205-'


What you want is the basename of the path, less the extension:

py> import os
py> path = '/var/tmp/02_80_5309_4444_2017_01_19_08-40-30_4205_0.zip'
py> os.path.basename(path)
'02_80_5309_4444_2017_01_19_08-40-30_4205_0.zip'
py> os.path.splitext(os.path.basename(path))[0]
'02_80_5309_4444_2017_01_19_08-40-30_4205_0'

That's a bit unwieldy, so create a helper function:

import os
def base(path):
    return os.path.splitext(os.path.basename(path))[0]

Now you can safely use this on your list:

for path in my_list:
    print(base(path))


Or if you want a new list, you can use a list comprehension:

filenames = [base(path) for path in my_list]

or the map() function:

# Python 2
filenames = map(base, my_list)

# Python 3
filenames = list(map(base, my_list))




-- 
Steve


More information about the Tutor mailing list