如果目录不存在,如何使用 Python 创建目录?
pythonprogrammingserver side programming
Python 内置了文件创建、写入和读取功能。在 Python 中,可以处理两种文件:文本文件和二进制文件(以二进制语言、0 和 1 编写)。虽然您可以创建文件,但当不再需要它们时,您可以删除它们。
以编程方式创建目录很简单,但您必须确保它们不存在。如果不存在,您将遇到困难。
示例 1
在 Python 中,使用 os.path.exists() 方法查看目录是否已存在,然后使用 os.makedirs() 方法创建目录。
内置 Python 方法 os.path.exists() 用于确定提供的路径是否存在。 os.path.exists() 方法会生成一个布尔值,该值是 True 还是 False,具体取决于路由是否存在。
Python 的 OS 模块 包括创建和删除目录(文件夹)、检索其内容、更改和识别当前目录等函数。要与底层操作系统交互,您必须首先导入 os 模块。
#python program to check if a directory exists import os path = "directory" # Check whether the specified path exists or not isExist = os.path.exists(path) #printing if the path exists or not print(isExist)
输出
执行上述程序时,将生成以下输出。
True Let's look at a scenario where the directory doesn't exist.
示例 2
内置 Python 方法 os.makedirs() 用于递归构建目录。
#python program to check if a directory exists import os path = "pythonprog" # 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!
示例 3
要创建目录,首先使用 os.path.exists(directory) 检查它是否已存在。然后您可以使用 −
创建它#python program to check if a path exists #if it doesn’t exist we create one import os if not os.path.exists('my_folder'): os.makedirs('my_folder')
示例 4
pathlib 模块包含表示文件系统路径并为各种操作系统提供语义的类。纯路径(提供纯计算操作而无 I/O)和具体路径(继承自纯路径但额外提供 I/O 操作)是两种类型的路径类。
# python program to check if a path exists #if path doesn’t exist we create a new path from pathlib import Path #creating a new directory called pythondirectory Path("/my/pythondirectory").mkdir(parents=True, exist_ok=True)
Example 5
# python program to check if a path exists #if path doesn’t exist we create a new path import os try: os.makedirs("pythondirectory") except FileExistsError: # directory already exists pass