[Tutor] scratching my head

Cameron Simpson cs at zip.com.au
Mon Aug 3 00:35:01 CEST 2015


On 02Aug2015 23:01, ALAN GAULD <alan.gauld at btinternet.com> wrote:
>On 02/08/15 22:44, Clayton Kirkwood wrote:
>>for dir_path, directories, files in os.walk(main_dir):
>>     for file in files:
>>#        print( " file = ", file)
>>#       if( ("(\.jpg|\.png|\.avi|\.mp4)$") not in file.lower() ):
>
>Python sees that as a single string. That string is not in your filename.
>
>>#        if(  (".jpg" or ".png" or ".avi" or ".mp4" )  not in file.lower()
[...]
>But you could use a loop:
>
>found = False
>for s in (".jpg",".png",".avi",".mp4"):
>    found = test or (s in file.lower())
>if not found: ...
>
>>         if(  ".jpg" not in file.lower() and
>>              ".png" not in file.lower() and
>>              ".avi" not in file.lower() and
>>              ".mp4" not in file.lower() ):
>
>Whether that's any better than your combined test is a moot point.

Alan has commented extensively on the logic/implementation errors. I have a 
suggestion.

Personally I'd be reaching for os.path.splitext. Untested example below:

  from os.path import splitext
  ....
  for dir_path, directories, files in os.walk(main_dir):
    for file in files:
      prefix, ext = splitext(file)
      if ext and ext[1:].lower() in ('jpg', 'png', 'avi', 'mp4'):
        ....

which I think is much easier to read.

BTW, I'd be using the variable names "filename" and "filenames" instead of 
"file" and "files": in python 2 "file" is a builtin function (though long 
deprecated by "open()") and in any case I'd (personally) expect such a name to 
be an _open_ file. As opposed to "filename", which is clearer.

Cheers,
Cameron Simpson <cs at zip.com.au>

Rudin's Law:
  If there is a wrong way to do something, most people will do it every time.
Rudin's Second Law:
  In a crisis that forces a choice to be made among alternative courses of
  action, people tend to choose the worst possible  course.


More information about the Tutor mailing list