0

small Python prog' to sort downloads folder by matching the extension,
I am getting a False (it seems to me) string match in the following. I searched but seemed to only find issues regarding REGEX matching, or more complex stuff!

seperate the extension

for filename in os.listdir(src_base_folder):
orig_title, orig_ext = os.path.splitext(filename)

make lower case for ease of matching and strip the leading "."
I suspect my issue is here somehow..

extension = str.lower(orig_ext)[1:]

The test below is working fine for everything except "S22F350FH.icm", a colorscheme file for setting up a monitor.

I print out the "extension" which shows as "icm" yet I am getting a FALSE match in this code against the extensions for various image types:

if extension == "jpg" or "jpeg" or "png" or "gif" or "bmp":  

Appreciate your thoughts.

Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
Dee
  • 191
  • 1
  • 11

2 Answers2

1

Instead of if extension == "jpg" or "jpeg" or "png" or "gif" or "bmp", you should use:

if extension in ["jpg", "jpeg", "png", "gif", "bmp"]:
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
1

The interpreter treats conditionals as follows:

if expr_1 or expr_2 or expr_3:

More concisely,

if (expr_1) or (expr_2) or (expr_3)

Evaluating your program, the interpreter treats if extension == "jpg" or "jpeg" or "png" or "gif" or "bmp" as:

if (extension == "jpg") or ("jpeg") or ("png") or ("gif") or ("bmp"):

Since non-empty strings are truthy, this will always evaluate to True. Instead, use what @Mayank suggested, if extension in ["jpg", "jpeg", "png", "gif", "bmp"]:.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • Ok, that's interesting, 'truthy', but also interesting that I have several other lines for matching other file types (PDF[pdf], Docs[xlsx,docx,odt,ods], ZIPS[zip, gz, tar]) and yet only this file *slips* through. O_O – Dee Oct 28 '20 at 07:12
  • 1
    @Dee try `bool("jpg")` and `bool("")`. Non-empty strings, when cast to a boolean, are `True`. This leads to the terminology *truthy*. – A.J. Uppal Oct 28 '20 at 17:09
  • thanks, I get it now; so my *if extension == "jpg"* is a poor choice of comparison for string(s). Mayank's answer is definitely working and much more concise as well. So a win win. I will rework my other code to try and remove the "truthy" comparisons - lucky I guess that they worked thus far? =) – Dee Oct 29 '20 at 08:08