In this guide, I will show you how to manage files and directories in Python! Use this to create things such as file explorers.
Before we start we need to import the OS module into Python, but luckily it is pre-installed, so all you need to add to your script is:
The OS module has a variety of Methods to allow File Management, the opening of Files and more! Here are a few of the common methods you will use:
|os.listdir(path)||Gives you a list that contains the names of directories in the path specified. e.g path = “c:/users”, it will then give you a list of all directories in c:/users.|
|os.remove(path)||Removes (deletes) the file. e.g path = “c:/users/newfile”, it will then remove the file at the path “c:/users/newfile”.|
|os.rename(file, newname)||Changes the file name. e.g file = “c:/users”, newname = “people”. It will change the file “c:/users” to “people”.|
|os.mkdir(path)||Makes a directory. e.g path = “c:/mypath”, this will create a directory called mypath in c:/.|
|os.rmdir(path)||Removes (deletes) the directory. This will only work if the directory is empty! e.g path = “c:/users/file/youtube”. It will remove the path “c:/users/file/youtube” if it is empty.|
If you wanted to list all files in a directory you would do so like this:
import os #Imports the OS module path = "c:/users/flynn/downloads" #This is the path directory = os.listdir(path) #This list all the directories in the path for file in directory: #Loops for each file in the directory print(file) #Prints every file in the directory
This is the output:
which is exactly what is in my downloads folder!
and that is the basics of using the OS module to Manage Files and directories using Python! If you liked this guide why not check out my Youtube channel for programming, development logs and more!