以编程方式创建目录很容易,但你需要确保它不存在。否则,你将面临一些问题。
创建不存在的目录
要在Python中创建一个不存在的目录,使用os.path.exists() 方法检查它是否已经存在,然后你可以使用os.makedirs()方法创建它。
os.path.exists()是一个内置的Python方法,用于检查指定路径是否存在。os.path.exists()方法返回一个布尔值,如果路径存在则为真,否则返回假。
os.makedirs()是一个内置的Python方法,用于递归地创建一个目录。
在处理目录时,我们需要将os模块导入我们的程序中:
import os
现在让我们定义一个路径并检查它是否存在:
import os
path = '/Users/krunal/Desktop/code/pyt/database'
# Check whether the specified path exists or not
isExist = os.path.exists(path)
print(isExist)
输出
True
它返回True,这意味着它确实存在。
让我们来看看路径不存在的情况。
import os
path = '/Users/krunal/Desktop/code/database'
# Check whether the specified path exists or not
isExist = os.path.exists(path)
print(isExist)
# Specify path
path = '/Users/krunal/Desktop/code/pyt/database/app.py'
# Check whether the specified path exists or not
isExist = os.path.exists(path)
print(isExist)
輸出
False
好的,所以上面代码中新修改的路径并不存在。
在这里,我们可以安全地创建一个指定路径的新目录,因为它并不存在。
要创建一个新的目录,请使用os.makedirs()函数。
但在此之前,我们将使用if not操作符来检查它是否不存在并创建一个新目录。
import os
path = '/Users/krunal/Desktop/code/database'
# Check whether the specified path exists or not
isExist = os.path.exists(path)
if not isExist:
# Create a new directory because it does not exist
os.makedirs(path)
print("The new directory is created!")
输出
The new directory is created!
这就是了。我们成功地创建了一个以前不存在的目录。
如果你重新运行这段代码,它将不会再创建任何目录,因为现在它已经存在。
默认模式是0o777(八进制)。在一些系统中,模式被忽略了。在使用它的地方,当前的umask值首先被屏蔽掉。如果existence_ok为False(默认值),如果目标目录已经存在,就会引发一个OSError。
makedirs()函数的existence_ok命名参数
os.makedirs()函数将exists_ok参数作为一个可选参数,因为它有一个默认值;默认情况下,exists_ok被设置为False。例如,如果你试图使用makedirs来创建一个已经存在的路径,它将不会被确定。
如果你想防止错误信息被抛出,在调用makedirs()时将exists_ok设置为True。
import os
path = '/Users/krunal/Desktop/code/database'
os.makedirs(path, exist_ok=False)
print("The new directory is created!")
所以这就是如何在 Python 中用 makedirs() 轻松地创建目录和子目录。
这就是在Python中创建一个不存在的目录的方法。