I'm writing a small program in python that automate the files management after downloading to specific folders and i'm getting this error can any one help ?
The code :
def check_image_files(self, entry, name): # * Checks all Image Files
for image_extension in image_extensions:
if name.endswith(image_extension == ".ico" ):
dest_img = dest_dir_icon
elif name.endswith(image_extension == ".psd"):
dest_img = dest_dir_PhotoShop
elif name.endswith(image_extension == ".ai", ".eps"):
dest_img = dest_dir_png
elif name.endswith(image_extension == ".png"):
dest_img = dest_dir_png
else:
dest_img = dest_dir_image or name.endswith(image_extension.upper())
move_file(dest_img, entry, name)
logging.info(f"Moved image file: {name}")
Error :
if name.endswith(image_extension == ".ico" ):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: endswith first arg must be str or a tuple of str, not bool
I tried to change operators and i googled my error i didn't find any helpful solutions
CodePudding user response:
.endswith
doesn't take named parameters like "image_extension". Just do if name.endswith(".ico" ):
CodePudding user response:
The error you are getting is because image_extension == ".ico"
will return a boolean( True or False) but .endswith() takes a string as an argument. So if you want to check if name ends with „.ico“ you can do this:
if name.endswith(".ico"):
CodePudding user response:
The argument to endswith()
must be the string to test as the ending (or a list of strings). You're passing the boolean result of comparing each extension with image_extension
.
You shouldn't have the for
loop in the first place, since you don't need to do anything repeatedly. endswith()
can be given a list of ending strings to test, so you can just use .endwith(image_extensions)
. Then you can test the specific extensions to get the intended icon.
And the move_file()
call shouldn't be in the else:
block, it should be done for any extension.
def check_image_files(self, entry, name): # * Checks all Image Files
lower_name = name.lower()
if lower_name.endswith(image_extension):
if lower_name.endswith(".ico" ):
dest_img = dest_dir_icon
elif lower_name.endswith(".psd"):
dest_img = dest_dir_PhotoShop
elif lower_name.endswith((".ai", ".eps")):
dest_img = dest_dir_png
elif lower_name.endswith(".png"):
dest_img = dest_dir_png
else:
dest_img = dest_dir_image
move_file(dest_img, entry, name)
logging.info(f"Moved image file: {name}")
else:
logging.error(f"Not an image file: {name}")