深度阅读

How to create a directory in Python

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

To create a directory in Python, you can use the os.makedirs() method. This function creates all the intermediate-level directories in the specified path if they do not already exist. Here is an example:

import os

directory = 'my_folder'
if not os.path.exists(directory):
    os.makedirs(directory)

In this example, we first define the name of the folder we want to create. We then check if the folder already exists using the os.path.exists() method. If the folder doesn’t exist, we create it using os.makedirs().

Alternatively, you can use the os.mkdir() method to create a single-level directory. Here is an example:

import os

directory = 'my_folder'
if not os.path.exists(directory):
    os.mkdir(directory)

In this example, we create a single-level directory instead of creating all intermediate-level directories.

博客作者

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