即使文件夹存在,os.path.isdir()也会返回False [英] os.path.isdir() returns False even when folder exists

查看:296
本文介绍了即使文件夹存在,os.path.isdir()也会返回False的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个脚本,它必须检查所有指定的文件夹是否真的存在。
我发现我必须使用os.path.isdir()与绝对路径。



我有以下的目录结构:

  X:\ 
pythonscripts \
files\
Films \
Series \
src\

当我打开我的python命令行并尝试是否实际存在文件夹时,我得到以下内容:

 >>> import os 
>>> os.path.isdir('X:\pythonscripts\src')
True
>>> os.path.isdir('X:\pythonscripts\files')
False
>>> os.path.isdir('X:\pythonscripts\files\Films')
False
>>> os.path.isdir('X:\pythonscripts\files\Series')
False

这很奇怪,因为当我将这些路径复制并粘贴到Windows资源管理器时,我可以毫无问题地访问它们。我检查了权限,所有文件夹都具有相同的权限。有没有人知道我在做什么错了?
$ b $ pre $ os.path.isdir('X:\\pythonscripts\\src')

或使用原始字符串:

  os.path.isdir(r'X:\pythonscripts\src')


$ b $

无法转义;> '\f'
'\x0c'
>>> print'\f'

>>> print'\\f'
\f
>>> print r'\f'
\f


I'm currently writing a script which has to check if all specified folders actually exist. I found out I have to use os.path.isdir() with absolute paths.

I have the following directory structure:

X:\
  pythonscripts\
    files\
      Films\
      Series\
    src\

When I open op my python command line and try if the folders actually exist, I get the following:

>>> import os
>>> os.path.isdir('X:\pythonscripts\src')
True
>>> os.path.isdir('X:\pythonscripts\files')
False
>>> os.path.isdir('X:\pythonscripts\files\Films')
False
>>> os.path.isdir('X:\pythonscripts\files\Series')
False

Which is odd, because when I copy and paste these paths into Windows Explorer, I can access them without problems. I checked permissions and all folders have the same permissions on them. Does anyone know what I'm doing wrong?

解决方案

Escape backslash (\)

os.path.isdir('X:\\pythonscripts\\src')

or use raw string:

os.path.isdir(r'X:\pythonscripts\src')


without escape, you get wrong path:

>>> '\f'
'\x0c'
>>> print '\f'

>>> print '\\f'
\f
>>> print r'\f'
\f

这篇关于即使文件夹存在,os.path.isdir()也会返回False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆