Table of Contents
Directories in a file system are just as important as files, and Python makes working with both pretty easy using the os
module.
Creating a new Directory
You can create a new directory using the mkdir
function, which is short for "make directory":
PYTHONimport os
os.mkdir("new_folder")
Your new folder has been created!
Getting your Current Working Directory
Just like when you're using the command line, sometimes you just want to know what directory you are currently working off of so you know how to get to where you want to go.
There is a function you can run to print that out for you, the getcwd()
function which stands for "get current working directory".
PYTHONimport os
print(os.getcwd())
BASHC:\Users\Sabe\Desktop
Easy enough!
Changing your Current Working Directory
Now that you know where you are, you might want to change it to work from another directory. You can do this using the chdir()
function which stands for "change directory":
PYTHONimport os
print(os.getcwd())
os.chdir("C:\\Users\\")
print(os.getcwd())
BASHC:\Users\Sabe\Desktop
C:\Users
Deleting a Directory
You can delete a directory using the rmdir()
function, which stands for "remove directory", and passing in the path to the directory you want removed:
PYTHONimport os
os.rmdir("test")
There goes the test
directory!
- Create an RSS Reader in Node
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Getting Started with Moment.js
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js