【问题标题】:os.path.isdir returns false when folder exists?当文件夹存在时,os.path.isdir 返回 false?
【发布时间】:2014-07-25 21:26:48
【问题描述】:

我有以下代码检查目录是否存在

def download(id, name, bar):
    cwd = os.getcwd()
    dir = os.path.join(cwd,bar)
    partial = os.path.join(cwd, id + ".partial")
    print os.path.isdir(dir)
    if(os.path.isdir(dir)):
        print "dir exists"
        dir_match_file(dir, bar)
    else:
        print dir

对于实际存在的目录,它返回“False”。这是输出:

False
/scratch/rists/djiao/Pancancer/RNA-seq/CESC/TCGA-BI-A0VS-01A-11R-A10U-07

当我进入 python 交互会话并输入 os.path.isdir("/scratch/rists/djiao/Pancancer/RNA-seq/CESC/TCGA-BI-A0VS-01A-11R-A10U-07") ,它返回“真”。

文件夹存在时为什么会说false?

【问题讨论】:

  • 您是否在两个实例中以同一用户身份运行代码?
  • print dir 更改为print(repr(dir))。让我们看看是否有一些“隐形”字符,例如末尾的 CR/LF。
  • @unutbu 啊,最后有一个'\n'。我从带有 readlines 的文件中读取 bar。猜猜我必须把它脱掉。 repr 对字符串到底做了什么?
  • repr(obj) 返回一个str,它旨在作为对象的明确表示。使用repr 检查basestringsstrs 或unicode)很有用,因为它会准确地告诉您basestring 由哪些字节或代码点组成。
  • 您应该知道dir 是一个内置函数。最好选择不同的变量名

标签: python os.path


【解决方案1】:

download 中的 dir 末尾有空格,而交互式会话中定义的 dir 没有。差异是通过打印repr(dir) 发现的。

In [3]: os.path.isdir('/tmp')
Out[3]: True

In [4]: os.path.isdir('/tmp\n')
Out[4]: False

【讨论】:

    猜你喜欢
    • 2010-10-29
    • 2015-09-21
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    相关资源
    最近更新 更多