question about endswith()

Grant Edwards invalid at invalid.invalid
Thu Mar 3 20:46:35 EST 2011


On 2011-03-04, Matt Funk <mafunk at nmsu.edu> 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

I was unable to run that code:

$ cat testit.py

for filename in files:
    if (any(filename.endswith(x) for x in extensions)):
        print filename

$ python testit.py

Traceback (most recent call last):
  File "testit.py", line 1, in <module>
    for filename in files:
NameError: name 'files' is not defined

> 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'?

Dunno.  You didn't provide enough information for us to answer your
question: the code you posted won't run and don't tell us what values
you're using for any of the variables.

Here's a piece of runnable code that I think does what you want:

$ cat testit.py
files = ["foo.bar", "foo.baz", "foo.bax"]
extensions = [".baz",".spam",".eggs"]

for filename in files:
    if (any(filename.endswith(x) for x in extensions)):
        print filename

$ python testit.py
foo.baz

-- 
Grant



More information about the Python-list mailing list