如何检查目录是否存在?
当前回答
#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')
其他回答
以下代码检查代码中引用的目录是否存在,如果您的工作场所中不存在,则会创建一个:
import os
if not os.path.isdir("directory_name"):
os.mkdir("directory_name")
是的,使用os.path.exists()。
太近了!如果传入当前存在的目录名,os.path.isdir将返回True。如果它不存在或不是目录,则返回False。
步骤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中是否存在目录?
有一个方便的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'