os.path.isfile() 判断问题

来源:互联网 发布:排列组合公式算法例题 编辑:程序博客网 时间:2024/05/29 04:11

运行环境

python3


运行以下代码:

可以得到当前目录的下的目录

for x in os.listdir('.'):    if os.path.isdir(x):        print (x)

如果将 os.listdir() 的参数替换为 其他路径,将会出错,比如

for x in os.listdir('/root'):    #print (x)#若此处将 x 输出 即可知道错误的原因 , x 的值 只是文件名 ,并 不是路径    if os.path.isdir(x):        print (x)


运行后将会发现,第二个  print( )   函数  无论改为什么路径都不会有任何输出


将第二段代码改为

for x in os.listdir('/root'):    if os.path.isdir(os.path.join('/root',x)):        print (x)

这样输出就正确了


总结:

os.path.isdir( ) 函数的参数如果只写文件名,则默认为当前路径,因此想要判断自定义的路径  必须使用  连接函数  os,path,join( ) 将路径连接起来






0 0