if command with python os path module

Viewed 58

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 ?

3 Answers

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()

You are looking for something like the below (no need for elif)

import os


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


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


line()

The problem is in your boolean variable you have to use True instead of true and False instead of false as below.

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()

You don't necessarily need a check == True actually instead you can do it like above.

Related