python - if 命令与 python os 路径模块

标签 python python-os

所以..这是我的代码:

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

我的目标是......仅当输入路径可用时才应继续执行代码

我认为这会起作用,但不幸的是它不起作用......任何人都可以解释为什么它不起作用......以及解决方案应该是什么?

最佳答案

我知道它已经得到答复,但它并没有指出问题。 修复方法很简单。你做错的事情是你使用了小写的 true 和 false。 但在Python中这是“True”和“False”。如您所见,第一个字母需要大写。

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

但你也可以这样做。而不是像elif那样写。并且==正确。 您不需要指定 == 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()

关于python - if 命令与 python os 路径模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69325565/

相关文章:

python - 在 VS Code 终端中显示耗时

python - 用间隔之间的每日值填充索引

python - 如何通过网络驱动器快速获取 .csv 文件的最后一行?

python - 如何使 OS.popen 命令的输出成为选择菜单列表?

python - 如何读取从 os.listdir 获取的文件内容?

python - 是否可以在不知道键的情况下排除 deepdiff 中的字典路径

python - 如何在 SQLAlchemy ORM 中查询多个表

Python Matplotlib Colorbar/Colormap 设置

python - 如何获取目录中最后修改的文件?