In Python, a directory is a collection of files and subdirectories that are organized hierarchically. Directories are also commonly known as folders. You can create, delete, and navigate directories using the built-in os
and shutil
modules in Python.
Here are a few examples of how to work with directories in Python:
Create a new directory:
To create a new directory in Python, you can use the os.mkdir()
function. Here’s an example:
import os
os.mkdir('my_directory')
This code will create a new directory called “my_directory” in the current working directory.
Create a new directory and its parent directories:
If you want to create a new directory and its parent directories (if they don’t already exist), you can use the os.makedirs()
function. Here’s an example:
import os
os.makedirs('my_directory/sub_directory')
This code will create a new directory called “my_directory” and a subdirectory called “sub_directory” inside it.
Delete a directory:
To delete a directory in Python, you can use the os.rmdir()
function. Here’s an example:
import os
os.rmdir('my_directory')
This code will delete the “my_directory” directory.
Note: The os.rmdir()
function can only delete empty directories. If the directory contains any files or subdirectories, you will need to use the shutil.rmtree()
function to delete it.
List all files and directories in a directory:
To list all the files and directories in a directory, you can use the os.listdir()
function. Here’s an example:
import os
files = os.listdir('my_directory')
print(files)
This code will print a list of all the files and directories in the “my_directory” directory.
Check if a directory exists:
To check if a directory exists in Python, you can use the os.path.exists()
function. Here’s an example:
import os
if os.path.exists('my_directory'):
print('The directory exists')
else:
print('The directory does not exist')
This code will check if the “my_directory” directory exists and print a message accordingly.
These are just a few examples of what you can do with directories in Python. There are many more built-in functions and operations available that you can use to work with directories and files in Python.