Python VS and Pycharm behavior [closed]

This script is returning True on the os.path.exists for a random string why
Screenshot Of Visual Studio Code IDE with Run in Output

import os


def checkDir(folder):
    folderStr=str(folder)
    print(os.path.exists(folderStr))
    if os.path.exists(folderStr)== True:
        pass
    else:
        try:
            for x in range(1,len(folderStr.split("/"))+1):
                if os.path.exists(("/".join((folderStr.split("/"))[:x]))):
                    pass
                else:
                    if "." not in ("/".join((folderStr.split("/"))[:x])):
                        os.mkdir(("/".join((folderStr.split("/"))[:x])))
        except OSError as error:
            return False
        
print(checkDir("test"))

I expected the code to print False not True

Also Have tried Using different PC (Works) tried Using different IDE (Same Problem)

  • 3

    Not to be dumb, but have you verified that you do not have a folder in either your root directory or the root directory of the script that is called test? I would suggest you try checkDir(“kljafsdklja”) or some other truly random string to be more certain that it isn’t finding some actual directory that just happens to be called “test”

    – 

  • 1

    If Python tells you that a path exists, then it’s very unlikely that the path doesn’t exist. Maybe you look in the wrong folder. If you use os.path.exists with a relative path it will look in the current working directory and that may or may not be the same directory where your script is.

    – 

  • I did not think of that and U are correct It is in the Root folder of the code I am sorry Did not think of that thank you XD Thanks for the Help

    – 




Okay if anyone end Up making this Embarrassing mistake Here is what is happening I did not think about this but @Sam Spade pointed this out

Look in your Local files where the code is located but trusts me there is a folder somewhere that has that name either in your root folder or some where just figure out where this is and kill it

Any one wondering how my new code looks is

    #Checks if the dir excist and if not it creates it
#used in cmdBuild
def checkDir(self,folder):
    folderStr=str(folder)
    folderAb=os.path.abspath(folderStr)
    #Test with pathlib if dir exists implement pathlib to test for excists on folder rather then os.path
    if os.path.exists(folderAb)== True:
        pass
    elif os.getcwd() in os.path.abspath(__file__):
        return False
    else:
        try:
            for x in range(1,len(folderAb.split("/"))+1):
                if os.path.exists(("/".join((folderAb.split("/"))[:x]))):
                    pass
                else:
                    if "." not in ("/".join((folderAb.split("/"))[:x])):
                        os.mkdir(("/".join((folderAb.split("/"))[:x])))
        except OSError as error:
            return False

Leave a Comment