我有以下代码来检查目录是否存在
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") 时,它返回“true”。
为什么文件夹存在时却显示false?
dir
中的download
末尾有空格,而交互会话中定义的dir
则没有。通过打印repr(dir)
发现了差异。
In [3]: os.path.isdir('/tmp')
Out[3]: True
In [4]: os.path.isdir('/tmp\n')
Out[4]: False
我在使用
"~"
引用目录来表示 Ubuntu 上的主目录时遇到了这个问题。通常,当将其保留为 "~"
时,路径会起作用,但有时却不起作用。我不知道为什么它并不总是有效。
在这种情况下,解决方案是将路径包裹在
os.path.expanduser
中,将 "~"
标准化为主目录的绝对路径。
In [1]: import os
In [2]: os.path.isdir("~/Datasets")
Out[2]: True
In [3]: os.path.isdir("~/Datasets/cifar10")
Out[3]: False
In [4]: os.path.isdir(os.path.expanduser("~/Datasets/cifar10"))
Out[4]: True