How to create a new folder in python?

Member

by kelly , in category: Python , 2 years ago

How to create a new folder in python?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by emerald , 2 years ago

@kelly To create a directory, you can use the os library and its .mdkir() method, example shown bellow:

1
2
3
import os

os.mkdir("Some_Folder") # Making directory called "Some_Folder"

Member

by viviane , a year ago

@kelly 

You can create a new folder (also known as a directory) in Python using the os module. The os module provides a platform-independent way of working with files and directories.


Here's an example code snippet that creates a new directory named "new_folder" in the current working directory:

1
2
3
4
5
6
7
8
9
import os

directory = "new_folder"

if not os.path.exists(directory):
    os.makedirs(directory)
    print("Directory created successfully!")
else:
    print("Directory already exists!")


In this code, the os.path.exists() function is used to check whether the directory already exists. If it does not exist, the os.makedirs() function is used to create the directory.


The os.makedirs() function creates all intermediate-level directories in the specified path. If any of the intermediate-level directories already exist, os.makedirs() will not raise an error.


The output of the code will depend on whether the directory already exists or not. If the directory is created successfully, the message "Directory created successfully!" will be printed. If the directory already exists, the message "Directory already exists!" will be printed.