Search code examples
pythonpython-os

if command with python os path module


so.. this is my code :

import os

def line():
    pathInput = input("Type the addres of your file")
    pathExists = os.path.exists(pathInput)
    if(pathExists == true):
        something()
    elif(pathExists == false):
        print('said path is not avaialable')

def something():
    print("yet to work on it")

line()

my goal is that... it should continue on with the code only if the input path is available

i thought this would work but unfortunately it doesnt.... can anyone explain why it doesnt.. and what should the solution be ?


Solution

  • I know it's get answered already but it's doesn't point out the problem. The fix is simple. What you are doing wrong is you are using small case true and false. But in python this is "True" and "False". As you can see first letter needs to capitalize.

    import os
    
    def line():
        pathInput = input("Type the addres of your file")
        pathExists = os.path.exists(pathInput)
        if(pathExists == True):
            something()
        elif(pathExists == False):
            print('said path is not avaialable')
    
    def something():
        print("yet to work on it")
    
    line()
    

    But you can also do. Instead of writing like elif. And == True. You don't need to specify == True.

    import os
    
    def line():
        pathInput = input("Type the addres of your file")
        pathExists = os.path.exists(pathInput)
        if(pathExists):
            something()
        else:
            print('said path is not avaialable')
    
    def something():
        print("yet to work on it")
    
    line()