python创建目录和子目录
时间: 2023-11-16 22:59:36 浏览: 92
在Python中,可以使用os模块来创建目录和子目录。具体步骤如下:
1. 导入os模块:import os
2. 使用os.makedirs()函数创建目录和子目录,例如:os.makedirs('F:/Code/test/subdir1/subdir2')
这个函数会自动创建所有不存在的目录,如果目录已经存在,则不会进行任何操作。
如果需要在指定目录下创建一个空文件夹,可以使用os.mkdir()函数,例如:os.mkdir('F:/Code/test/emptydir')
相关问题
python 创建目录
使用Python可以使用`os`模块创建目录。以下是示例代码:
```python
import os
# 创建单层目录
os.mkdir('testdir')
# 创建多层目录
os.makedirs('parentdir/testdir')
```
在这个示例中,我们使用`os.mkdir()`函数创建了一个名为`testdir`的目录,使用`os.makedirs()`函数创建了一个名为`testdir`的子目录,子目录位于名为`parentdir`的父目录下。
请注意,如果目录已经存在,则会引发异常。为了避免这种情况,您可以在调用之前检查目录是否存在,例如:
```python
if not os.path.exists('testdir'):
os.mkdir('testdir')
```
python 递归创建目录
递归创建目录是指在一个目录下创建其所有不存在的子目录。在Python中,我们可以使用os模块的os.makedirs()函数来实现这个功能。
解析:
1. 导入os模块
2. 定义一个函数,接收一个参数,即要创建的目录路径
3. 使用os.makedirs()函数创建目录
代码:
```python
import os
def create_recursive_directory(path):
try:
os.makedirs(path)
print(f"目录 {path} 创建成功")
except FileExistsError:
print(f"目录 {path} 已经存在")
# 示例
create_recursive_directory("test_dir/sub_dir")
```