如何检查目录是否存在?
os.stat
,以查看该目录是否同时存在并且是一个目录。
os.stat
来区分文件目录的方法。当路径无效时,无论是文件还是目录,它都会引发 OSError
。此外,检查后的任何代码也容易受到竞争条件的影响。
os.stat
仅对目录使用 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
Python 3.4 将 the pathlib
module 引入标准库,它提供了一种面向对象的方法来处理文件系统路径。 Path
对象的 is_dir()
和 exists()
方法可用于回答以下问题:
In [1]: from pathlib import Path
In [2]: p = Path('/usr')
In [3]: p.exists()
Out[3]: True
In [4]: p.is_dir()
Out[4]: True
路径(和字符串)可以用 /
运算符连接在一起:
In [5]: q = p / 'bin' / 'vim'
In [6]: q
Out[6]: PosixPath('/usr/bin/vim')
In [7]: q.exists()
Out[7]: True
In [8]: q.is_dir()
Out[8]: False
Pathlib 也可通过 the pathlib2 module on PyPi. 在 Python 2.7 上使用
p / 'bin' / 'vim'
?
很近!如果您传入当前存在的目录的名称,os.path.isdir
将返回 True
。如果它不存在或不是目录,则返回 False
。
os.path.isdir(path) or os.makedirs(path)
Path(path).mkdir(parents=True, exist_ok=True)
在一个操作中创建一个嵌套路径。
是的,使用 os.path.exists()
。
os.path.isdir
将实现这一点。
我们可以检查 2 个内置函数
os.path.isdir("directory")
它将给出 boolean true 指定的目录可用。
os.path.exists("directoryorfile")
如果指定的目录或文件可用,它将给出布尔值 true。
检查路径是否为目录;
os.path.isdir("directorypath")
如果路径是目录,将给出布尔值 true
以下代码检查代码中引用的目录是否存在,如果它在您的工作场所中不存在,则创建一个:
import os
if not os.path.isdir("directory_name"):
os.mkdir("directory_name")
如:
In [3]: os.path.exists('/d/temp')
Out[3]: True
可能会折腾一个os.path.isdir(...)
来确定。
如果目录不存在,您可能还需要创建目录。
Source,如果它仍然存在于 SO 上。
==================================================== ====================
在 Python ≥ 3.5 上,使用 pathlib.Path.mkdir
:
from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)
对于旧版本的 Python,我看到两个质量很好的答案,每个都有一个小缺陷,所以我会给出我的看法:
尝试 os.path.exists
,并考虑创建 os.makedirs
。
import os
if not os.path.exists(directory):
os.makedirs(directory)
如评论和其他地方所述,存在竞争条件 - 如果在 os.path.exists
和 os.makedirs
调用之间创建目录,则 os.makedirs
将失败并返回 OSError
。不幸的是,一揽子捕获 OSError
并继续并不是万无一失的,因为它会忽略由于其他因素(例如权限不足、磁盘已满等)而导致创建目录失败的情况。
一种选择是捕获 OSError
并检查嵌入的错误代码(请参阅 Is there a cross-platform way of getting information from Python’s OSError):
import os, errno
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise
或者,可能有第二个 os.path.exists
,但假设另一个在第一次检查之后创建了目录,然后在第二次检查之前将其删除——我们仍然可能被愚弄。
根据应用程序的不同,并发操作的危险可能大于或小于文件权限等其他因素带来的危险。在选择实现之前,开发人员必须更多地了解正在开发的特定应用程序及其预期环境。
现代版本的 Python 通过公开 FileExistsError
(在 3.3+ 中)对这段代码进行了相当多的改进......
try:
os.makedirs("path/to/directory")
except FileExistsError:
# directory already exists
pass
...并通过允许 a keyword argument to os.makedirs
called exist_ok
(在 3.2+ 中)。
os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.
os 为您提供了很多这样的功能:
import os
os.path.isdir(dir_in) #True/False: check if this is a directory
os.listdir(dir_in) #gets you a list of all files and directories under dir_in
如果输入路径无效,listdir 将抛出异常。
#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')
os.makedirs('mydir')
而不是 os.system(...)
有一个方便的 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'
两件事情
检查目录是否存在?如果没有,请创建一个目录(可选)。
import os
dirpath = "<dirpath>" # Replace the "<dirpath>" with actual directory path.
if os.path.exists(dirpath):
print("Directory exist")
else: #this is optional if you want to create a directory if doesn't exist.
os.mkdir(dirpath):
print("Directory created")
第一步:导入 os.path 模块 在运行代码之前导入 os.path 模块。
import os.path
from os import path
第二步:使用 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() – 如果 path 是 File,则返回 True。
os.path.isdir() - 如果路径是目录,则返回 True。
pathlib.Path.exists() - 如果路径或目录确实存在,则返回 True。 (在 Python 3.4 及以上版本中)
不定期副业成功案例分享
existing = filter(os.path.isdir(['/lib', '/usr/lib', '/usr/local/lib'])
map
,但在一般情况下,您调用带有参数和括号的函数。此外,您的示例中有一些错字。大概你的意思是filter(os.path.isdir, ['/lib', '/usr/lib', '/usr/local/lib'])
。os.path.isfile(path)
。