如何检查目录是否存在?
当前回答
步骤1:导入os.path模块在运行代码之前导入os.path模块。
import os.path
from os import path
步骤2:使用path.exists()函数path.exists()方法用于查找文件是否存在。
path.exists("your_file.txt")
步骤3:使用os.path.isfile()我们可以使用isfile命令来确定给定输入是否为文件。
path.isfile('your_file.txt')
步骤4:使用os.path.isdir()我们可以使用os.path.dir()函数来确定给定的输入是否是目录。
path.isdir('myDirectory')
这是完整的代码
import os.path
from os import path
def main():
print ("File exists:"+str(path.exists('your_file.txt')))
print ("Directory exists:" + str(path.exists('myDirectory')))
print("Item is a file: " + str(path.isfile("your_file.txt")))
print("Item is a directory: " + str(path.isdir("myDirectory")))
if __name__== "__main__":
main()
pathlibPath.exists()对于Python 3.4
Pathlib模块包含在Python 3.4和更高版本中,用于处理文件系统路径。Python使用面向对象技术检查文件夹是否存在。
import pathlib
file = pathlib.Path("your_file.txt")
if file.exists ():
print ("File exist")
else:
print ("File not exist")
os.path.exists()–如果路径或目录确实存在,则返回True。os.path.isfile()–如果路径为File,则返回True。os.path.isdir()–如果路径为Directory,则返回True。pathlib.Path.exists()–如果路径或目录确实存在,则返回True。(在Python 3.4及以上版本中)
文章参考:如何检查Python中是否存在目录?
其他回答
仅提供os.stat版本(python 2):
import os, stat, errno
def CheckIsDir(directory):
try:
return stat.S_ISDIR(os.stat(directory).st_mode)
except OSError, e:
if e.errno == errno.ENOENT:
return False
raise
太近了!如果传入当前存在的目录名,os.path.isdir将返回True。如果它不存在或不是目录,则返回False。
以下代码检查代码中引用的目录是否存在,如果您的工作场所中不存在,则会创建一个:
import os
if not os.path.isdir("directory_name"):
os.mkdir("directory_name")
有一个方便的Unipath模块。
>>> from unipath import Path
>>>
>>> Path('/var/log').exists()
True
>>> Path('/var/log').isdir()
True
您可能需要的其他相关事项:
>>> Path('/var/log/system.log').parent
Path('/var/log')
>>> Path('/var/log/system.log').ancestor(2)
Path('/var')
>>> Path('/var/log/system.log').listdir()
[Path('/var/foo'), Path('/var/bar')]
>>> (Path('/var/log') + '/system.log').isfile()
True
您可以使用pip安装它:
$ pip3 install unipath
它类似于内置的pathlib。不同之处在于,它将每个路径都视为字符串(path是str的子类),因此如果某个函数需要字符串,则可以轻松地将其传递给path对象,而无需将其转换为字符串。
例如,这对Django和settings.py非常有用:
# settings.py
BASE_DIR = Path(__file__).ancestor(2)
STATIC_ROOT = BASE_DIR + '/tmp/static'
#You can also check it get help for you
if not os.path.isdir('mydir'):
print('new directry has been created')
os.system('mkdir mydir')
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录