[Tutor] scratching my head
Clayton Kirkwood
crk at godblessthe.us
Mon Aug 3 01:15:19 CEST 2015
> -----Original Message-----
> From: Tutor [mailto:tutor-bounces+crk=godblessthe.us at python.org] On
> Behalf Of Cameron Simpson
> Sent: Sunday, August 02, 2015 3:35 PM
> To: tutor at python.org
> Subject: Re: [Tutor] scratching my head
>
> 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.
Thanks, that should also help a lot. Now time to look at splitext, and the
ext and ext[1:. I appreciate your comments also about the variable names.
Any comments on the problems lower in the file?
Clayton
>
> 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.
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list