question about endswith()

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Mar 4 05:08:02 EST 2011


Matt Funk wrote:
> Hi Grant,
> first of all sorry for the many typos in my previous email.
>
> To clarify, I have a python list full of file names called 'files'.
> Every single filename has extension='.hdf' except for one file which has
> an '.hdf5' extension. When i do (and yes, this is pasted):
>         for filename in files:
>             if (any(filename.endswith(x) for x in extensions)):
>                 print filename
>
> However, it will print all the files in list 'files' (that is all files
> with file extension '.hdf'). My question is why it doesn't just print
> the filename with extensions '.hdf5'?
>
> thanks
> matt
>
>   
Matt, in the code above your are iterating through the files, and if an 
hdf5 is in the list, you print the current element. Since the hdf5 will 
always be in that list, for each element you print it.

test.py:

import os

files = ['a.hdf', 'b.hdf5', 'c.hdf']
hdf5 =  [_file for _file in files if os.path.splitext(_file)[1] == '.hdf5']
print hdf5



 > python test.py
['b.hdf5']

JM




More information about the Python-list mailing list