如何检查目录是否存在?
当前回答
步骤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中是否存在目录?
其他回答
以下代码检查代码中引用的目录是否存在,如果您的工作场所中不存在,则会创建一个:
import os
if not os.path.isdir("directory_name"):
os.mkdir("directory_name")
是,使用os.path.isdir(路径)
是的,使用os.path.exists()。
仅提供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:
>>> import os
>>> os.path.isdir('new_folder')
True
对文件和目录使用os.path.exists:
>>> import os
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False
或者,您可以使用pathlib:
>>> from pathlib import Path
>>> Path('new_folder').is_dir()
True
>>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
False