if you will have nested directories in your path that endswith rules then os path exists dir  will return true  but os remove will fail  because it cannot remove directories  use os path isfile instead moreover  that fact than os path exists return to you that fact than file exists does not means that this file will exist when os remove call will be executed  why do not use try os remove filename except oserror some piece of s  t 