[Tutor] Filename match on file extensions
Steven D'Aprano
steve at pearwood.info
Wed Oct 3 07:49:07 CEST 2012
On Wed, Oct 03, 2012 at 03:14:16AM +0000, Dave Wilder wrote:
>
> Hello,
>
> Below is a snippet of a search I want to do for any file that contains the string "quarantine" in the filename.
> It works for picking up any file name containing "quarantine" except when "quarantine" is used as an extension.
Incorrect. It only picks up filenames that *begin* with "quarantine".
The critical code is:
i.lower().find("quarantine".lower()) == 0
which matches:
quarantineblahblahblah.txt
but not
blahblahquarantineblah.txt
The correct test for matching anywhere in the string is:
"quarantine" in i.lower()
By the way, it is misleading to call your loop variable "i". By
convention, i is used for integer loop variables. Since your loop
variable in this case is a file name, I would name it "filename":
for filename in files:
if "quarantine" in filename.lower():
...
Also, you might consider using the "glob" module, which is good for
finding filenames matching so-called globs:
"quarantine*.txt"
matches file names starting with quarantine, ending with .txt, and
anything at all in between.
--
Steven
More information about the Tutor
mailing list