python - 文件夹存在时 os.path.isdir 返回 false?

标签 python os.path

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

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 交互 session 并输入 os.path.isdir("/scratch/rists/djiao/Pancancer/RNA-seq/CESC/TCGA-BI-A0VS-01A-11R-A10U-07") ,它返回“真”。

为什么文件夹存在时提示false?

最佳答案

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

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

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

关于python - 文件夹存在时 os.path.isdir 返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24964751/

相关文章:

Python os.path.isdir 对于点返回 true

python - Pandas pd.merge "TypeError: string indices must be integers, not str"

python - 如何使用 Python 将文件夹放在 PATH 上?

Python 不等于 'for' 迭代

python - 如何在 matplotlib 2.0 中填充只有影线(无背景色)的区域

python - 如何在 Python 中的文件路径中间插入一个目录?

列表中的 Python os.path.join()

python - sklearn_extra 安装问题

Python找不到库但pycharm可以

python - 根据django中的请求动态设置数据库