【问题标题】:python os.path.isfile return with falsepython os.path.isfile 返回 false
【发布时间】:2015-06-05 06:02:36
【问题描述】:

我正在尝试从不同目录中搜索文件。我看到该文件确实存在,但 os.path.isfile 仍然返回 false。

由于我的文件可以在多个目录中

import os

me = "/user"
my_home = "/home"
my_direcotry = "/user/jsbt"
my_file =  "/myfile"

my_path = me + my_home + my_directory + my_file

print(my_path)

if (os.path.isfile( my_path )) is True:
print ("Path was found")
else:
print ("Path does not exist")
sys.exit(0)

上面这个总是会导致false,找不到文件。

但我确实找到了我的文件

有什么建议吗?

【问题讨论】:

  • 如果将 isfile 替换为存在会怎样?如果你这样做cat /user/home/user/jsbt/myfile
  • 我也尝试过使用 with exists 但同样的东西.. 结果是假的。
  • cat /user/home/user/jsbt/myfile 怎么样?它真的找到文件了吗?
  • 您上面显示的代码将导致多个错误,而不仅仅是缩进。向我们展示您实际使用的代码。
  • 对不起,伙计们打错了..我的错.. python 新手,已经很喜欢它了。 :) 修复它。

标签: python


【解决方案1】:

将扩展名添加到 my_file 并检查路径是否正确。

另外,不要使用is True。改为:

if (os.path.isfile( my_path )): # OR == True
    print ("Path was found")
    else:
    print ("Path does not exist")
    sys.exit(0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2019-04-16
    • 2017-01-22
    • 2020-11-17
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多