os.path.isdir(<whatever>) returns always True - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: os.path.isdir(<whatever>) returns always True (/thread-14518.html) |
os.path.isdir(<whatever>) returns always True - Fabrizio - Dec-04-2018 I am running a Python script, which is supposed to check whether a directory already exists: import os #!/usr/bin/env python source_dir = <inexistent directory> if (os.path.isdir(source_dir)): print "source directory not found" else: print "source directory found" os.system("ls -l " + source_dir)will always enter the else statement (directory found) for an non-existing directory and fail while trying to display the content of the inexistent directory. What is wrong in my code? My code runs correctly if run inside the console Python interpreter. My code always fails if run as a script on the very same console. Fabrizio RE: os.path.isdir(<whatever>) returns always True - Gribouillis - Dec-04-2018 It is similar to this if a == b: print('a and b are different') else: print('a and b are equal') RE: os.path.isdir(<whatever>) returns always True - Fabrizio - Dec-04-2018 @Gribouillis ?? Why it does not work then? I am not comparing things. I am checking if something is True or False. I just want to know whether a directory exists or not. How should I do it? It gives the wrong answer if I run it as a script. RE: os.path.isdir(<whatever>) returns always True - nilamo - Dec-04-2018 Look carefully at your code. I have a feeling that you've been looking at it so long, you've developed tunnel vision, and are skipping over parts of what's happening. (Dec-04-2018, 02:22 PM)Fabrizio Wrote:if (os.path.isdir(source_dir)): print "source directory not found" Here, let me help rewrite it for you: source_dir = "/literally_nowhere" directory_exists = os.path.isdir(source_dir) if directory_exists: print("It doesn't exist")Or, to break it down even further: if False: print("It's True")Obviously the else part is running: the condition you're checking is False.
|