深度阅读

4 Different Ways to mkdir in Python

作者
作者
2023年08月22日
更新时间
10.08 分钟
阅读时间
0
阅读量

Certainly, here are four different ways to create a directory in Python:

Using os.mkdir() method:

This method is used to create a new directory.

import os
path = "/path/to/directory"
os.mkdir(path)

Using os.makedirs() method:

This method is used to create a nested directory.

import os
path = "/path/to/directory"
os.makedirs(path)

Using Pathlib:

This method involves creating a Path object and then calling the mkdir() method on it.

from pathlib import Path
path = Path("/path/to/directory")
path.mkdir(parents=True, exist_ok=True)

Using subprocess.call() method:

This method involves calling the mkdir command with the help of subprocess.

import subprocess
path = "/path/to/directory"
subprocess.call(['mkdir', '-p', path])

Note that different methods may be more appropriate for different situations, depending on the specifics of your use case.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。