Python Tutorial: OS Module – Use Underlying Operating System Functionality
Video Title: Python Tutorial: OS Module – Use Underlying Operating System Functionality
hey there how’s it going everybody in this video we’re going to be learning about the OS module and some of the useful things that we can do with it now the OS module allows us to interact with the underlying operating system in several different ways so for example we can navigate the file system get file information look up and change the environment variables we can move files around and all kinds of useful stuff so let’s go ahead and take a look at a few of the things that we can do so first of all let’s go ahead and import the OS module now this is a built-in module so we don’t have to install any third-party libraries or anything like that now something useful when you’re working with a new module if you print out this built-in dir function and pass in the module that you are working with this will show us all of the attributes and methods that we have access to within this module and you can see here that with the OS module there are plenty to choose from now we’re not going to be going over each and every one of these but we will take a look at the ones that I kind of use on a regular basis and also the ones that I consider to be some of the most useful ok so for the first thing let’s just print out the current directory that we are in now to do this we can use OS dot get CWD and that stands for get current working directory and you can see here whenever I print this out it prints out that we are within this folder on the desktop called module OS so now what if we wanted to navigate to a new location on the filesystem so let’s say that we wanted to navigate to the desktop here so if I go ahead and just copy this path and this can be any path that you want I’m going to do an OS dot CH dir and that stands for change directory and I’m going to pass in the path as a string so if I save that and now I’m going to print out the current working directory after we change the directory now if I run that you can see that we were within this module folder and then we navigated to the desktop so now our current working directory is the desktop ok so now I’m going to take out this top print statement here okay so now let’s see what files and folders are here on the desktop now to do this we can use a method called list dir for list directory now you can pass a path into list directory but by default it will list the files and the folders in the current directory which is now our desktop since we change directory up here on line 4 so now if I run this then we can see the files and folders that are on the desktop ok so now what if we wanted to create a new folder on the desktop called let’s say OS demo 2 so let me grab this and I’ll just paste in OS demo – – here so now let’s say that we wanted to create a folder on the desktop with this name here now there are two different methods that we can use to do this we have OS dot make Durer and we can just pass in that string there as an argument and there is also oh s dot make ders now make ders and make Durer are pretty similar but make ders if you want to create a directory that’s a few levels deep then make ders will create all of the intermediate level directories that you need and make durst won’t do that so for example here if I wanted to do an OS demo and I wanted to do a subdirectory within here let’s say subtor one now if I tried to run this it’s going to give us an error because this top level here doesn’t exist yet now if we wanted to do this with make Thurs then it will go ahead and just create that top level for us so now I’m going to comment out the make der code now if I run that you can see that it ran fine and we have this OS demo 2 here and within that OS demo 2 it’s also going to have this subdirectory 1 so whenever I’m creating directories I usually use make doors even whenever I’m just making the top-level directory because I feel like it’s easier if I want to you know create a a tree structure just to you this one function but now let’s say that we wanted to delete these folders now the leading folders is kind of the same deal we have our ember and we have remove di RS so this is the same thing as make dirt and make ders the RM der will not remove the intermediate directories and remove d’oeuvres we’ll now I consider deleting directories recursively a little more dangerous than creating them recursively so usually whenever I am deleting folders I will use RM dur so that I can specifically delete the exact directory that I want removed but in this case since we want this entire demo tree gone anyway I’m just going to use RM ders here on this OS demo too and if I run that then we’re still printing out our list directory down here and you can see that that OS demo 2 was deleted okay now let’s say that we want to rename a file or a folder to do that we can use OS dot rename so let’s say that we want to rename this test.txt here let’s just rename this to let’s see demo dot txt so when you’re renaming files you want to pass in the original file name first and then the name of the new file that you want so if I save that and run it now it’s in a different order here but you can see that now this demo txt is within the desktop here and not the test dot txt ok so now let’s see how we can look at some information about our files so let’s say that we wanted to print out all the information about this demo dot txt file now to do this we can use OS dot stat and I’m actually going to have to print this out and for now I’m going to comment out the list directory there and I’m just going to print out this OS stat on the demo dot txt file okay so a few different things got printed out here and a lot of this can look like gibberish but you can look up in the documentation online what all of this means but a couple of useful ones that I usually use is we can see that we have the size here so if I copy that then I can just do a dot with the attribute there and I can print that out so the size of that file is bytes 20 bytes and let’s say for example that you wanted the last modification time that would be this M time right here so if I print it out this modification time here then you can see that it prints that out now that returns a timestamp and sometimes people don’t know how to get these timestamps and a human readable format so if we want to view this in an actual date time format and what we can do is we can do a from date/time import 8 time and I’m just going to let’s see I will save this as a variable here called mod time equals and then we’ll just do a print and a 8 time dot from time stamp and we will pass in that mod time and if I save that and run it then you can see it prints out a human readable form of that modified time timestamp and file information like that can be really useful like if you’re working with a web application that has a lot of files that have been updated or created recently and you want to know exactly when that was then this is a good way that you can do that within Python ok so now I’m just going to go ahead and get rid of all of this so far ok so now let’s say that we want to see the entire directory tree and files within the desktop now if you want to traverse the directory tree and print all of the directories and the files then you can use the OS dot walk method so OS dot Walk is a generator that yields a couple of three values as its walking the directory tree so for each directory that it sees it yields the directory path the direct within that path and the files within that path now I know that might sound a little confusing so let’s just go ahead and take a look at an example here so by default this traverses from the top down so if we wanted to start at the desktop then what do all we’d have to do here is now remember this yields a three value tuples so this is why we’re able to use this syntax so the first value is der path and then the next value is that there are names within that path and then the third value is the filenames within that path and we want to traverse this directory tree starting at the desktop so I could either copy the desktop path here or I could do an OS get current working directory that path end OS walk I’m just going to go ahead and pass in the path as a string and so now I’m just going to go ahead and print out all of these values from within the for loop here but just so you guys don’t have to watch me type I can just grab this from my snippets file and just paste this in here and indent that so let me go ahead and run this and I’ll show you what the walk method does and it can be extremely useful so what we did here is it started at the desktop as our current path and then it printed out all of the directories within the desktop and all of the files within the desktop and now it goes down each of these directories one at a time so now it goes into the demos folder and print out all the directories within the demo folder and all the files within that phone and within that path and then it goes down into that subdirectory and prints all the directories and then all the files and it keeps doing this until it goes through the entire tree of all of the directories and files on the root path which we chose as the desktop now this can be extremely useful if say that I had a file somewhere within one of the folders on my desktop but I didn’t remember exactly where it was then I could just use the OS dot walk method to go through and search through all of those files and folders on the desktop or like I was saying before if you had a web application and you wanted to keep track of all of the file information within a certain directory structure then you could just go through this OS dot walk method and go through all of the files and folders within your web application and collect file information that way so the OS walk method can be extremely useful for things like that okay so now let’s say that we want to access my home directory location by grabbing the home environment variable now we can get environment variables I’m just going to go ahead and delete these lines here now we can get environment variables by accessing OS dot environed to print out the OS dot environment out all of my environment variables but I have a lot of those so let’s just grab one so let’s say that I wanted to get my home environment variable which will be the location of my user’s home directory so let me just go ahead and print that out and run that and you can see that it captures my home directory there okay so now let’s say that I wanted to use this path that it gave me with this OS get home let’s say that I wanted to use that to create a new file within my home directory that I’ll just go ahead and create a file called let’s see test dot txt so the first thing that we’re going to want to figure out when we’re creating this file is what the path should be so how can we combine this path that we got from this home directory here and our file name into a single path for this new file now one thing that some people try is to just concatenate these so let’s say that I did a file path equal to the location of this home directory plus text txt now the problem with doing it this way is that it is it’s hard to remember if all of these slashes are and then in the correct positions or whether or not you could be missing a slash so for example if I print out this file path that we just created then you can see that we’re missing a slash here and sometimes it’s easy to forget that and some paths come with the slashes at the end and you can double slashes and things like that so in order to prevent this guesswork we can use the OS path module so the OS path module has a lot of useful methods for working with paths but the one that we’re going to use in this situation to combine the home directory with the filename is OS path join now what this does is it just joins two paths together and it takes away that guesswork that we were just talking about so here I’m going to do an OS path dot join and this takes in two arguments here so we’re going to have this home path be one argument and then this test.txt as the other one so if I save that I’m just going to comment out that print statement now if I save that and run it and you can see that we have a full path of this filename with the slash in the correct location so that takes all of the guesswork out of creating those paths and whether or not you need to add a slash in a certain location or not so you can see that it combined those and gave us the path that we were hoping for now that’s extremely useful again if you’re you know reading and writing a bunch of files to different locations and want to make sure that those paths are all created properly then you can go ahead and use that OS path join and know that it’s doing it correctly so now if we wanted to actually go ahead and create that file then we could just do a with open file path and then we could do an as F and write it and do you know an F dot right but I’m not going to actually create that file right now I will go into file creations and working with files in a later video but for now let’s go ahead and keep looking at some of the other useful methods that we have available here in an OS path so using this OS path it also has a few other useful methods that we can use here so we can do an OS path base name and what this will do is it will grab the file name of any path that we’re working on and this doesn’t have to be a real path so for example here this path and I’m typing in doesn’t exist this temporary text txt so let me go ahead and print out what this gives us so if I print that out you can see that the base name of this entire path is just text txt now if I only wanted the directory name of that path then instead of base name I could type in their name and print that out and you can see that it gives me temp now if I wanted both of those then I could use split and if I print that out you can see that it gives me the directory name first and the base name second so also using OS path you can check if a path exists so like I said before this was a fake path that doesn’t exist so if I want to check the existence I can do Oh s dot path dot exists and if I save that and run it you can see that that is false because this path actually doesn’t exist on the filesystem now two more methods that I use a lot if you did have a path that exists on the filesystem then sometimes temporary files might just be named without an extension so they might look something like this if you want to check if something is a directory or a file then you can do OS path that is der and it will return true if it’s a directory and you can do OS path that is file it will return true if it is a file now one more useful function that I end up using a lot is one called split ext now what this will do is it will split the file root and the extension or I should say the root of the path and the extension so if I was to save this and run it you can see that here we have this slash temp slash text test and for the second value we just have the extension T txt now this is a lot easier than trying to parse out the extension using string slicing or things like that it’s a lot easier just to split it off and then take the first value if you want the filename without the extension so that is a method that I end up using a lot for a file manipulation now just like we did with the OS module if you want to see everything that is available within though this OS path module then you can also print out the dir of that and you can see some of these that we’ve already worked with so we have their name exists is there is file and things like that but there’s a lot more useful information here as well okay so I think that is going to do it for this overview of the OS module now this module has a ton of functionality packed into it and we didn’t get to go over everything that it can do but these are the methods that I used most often and the ones that I find most useful so hopefully this video will give you some ideas for how you can use the OS module in your own projects if you do have any questions just feel free to ask in the comment section below and I’ll do my best to answer those questions be sure to subscribe for future videos and thank you all for watching
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
The best one i have ever seen in teaching coding . Thank you so much man
perfect understanding ,
Still useful
Corey Come back with AI tuts
very helpful
import os
for dirpath, dirnames, filenames in os.walk(os.getcwd()):
print("Path: ", dirpath)
print("Dir: ", dirnames)
print("File: ", filenames)
============================
import os
from datetime import datetime
print(os.listdir())
mod_time = os.stat('./document.txt').st_mtime
print(datetime.fromtimestamp(mod_time))
============================
import os
print(os.path.join(os.environ.get("Home"), 'main.py'))
Corey, I hope you are well today. 🤙🤙 I have been sober for one year. We got this.
great video, thank you!!
Yo this is included in summer analytics 2023 curriculum 👌
Thanks mate
Does anyone know if Corey or anyone on YT has made a pathlib module tutorial? It is alot easier to use than the os module.
this guy is so clear,
Windows Machine:
Any idea why the os.removedirs() is throwing a permission error?
I can create folders no problem with os.mkdir() and os.makedirs()
I can delete a folder no problem with os.rmdir()
But every time I use os.remove…. nvm, there's the problem.
If you are getting a permission error, make sure the function is typed correctly.
os.remove('insert directory')
is not the same thing as
os.removedirs()
well done
your examples doesn't work with Windows OS because of slashes
I love these videos. I just wanna know where I can find the snippets for dirpath.
anyone know why I keep getting the 'PermissionError: [Errno 1] Operation not permitted' when trying to change my directory? how can I give python permission to use os.listdir() on my desktop or on a folder in my desktop?
Really good explanation! I like this tutorial about os.path module too. Also good one. https://www.youtube.com/watch?v=cFn4D5PDc_c&t=3s&ab_channel=CodeonPuffic
Thanks!
Great video!
+ os.getcwd() => get current working directory
+ os.chdir(<path>) => change directory
+ os.listdir() => list directory
+ os.mkdir(<dirname>) => create a directory
+ os.makedirs(<dirname>) => make directories recursively
+ os.rmdir(<dirname>) => remove directory
+ os.removedirs(<dirname>) => remove directory recursively
+ os.rename(<from>, <to>) => rename file
+ os.stat(<filename>) => print all info of a file
+ os.walk(<path>) => traverse directory recursively
+ os.environ => get environment variables
+ os.path.join(<path>, <file>) => join path without worrying about /
+ os.path.basename(<filename>) => get basename
+ os.path.dirname(<filename>) => get dirname
+ os.path.exists(<path-to-file>) => check if the path exists or not
+ os.path.splitext(<path-to-file>) => split path and file extension
+ dir(os) => check what methods exists
nice
sir how can we remember all the methods you are teaching, it's so much also if someone knows linux the syntex gets confusing.
Thank you for explaining it clearly. Could you also explain about os.Pathlike
this got bit confusing
Thank you! I've been using the os module for years and had no idea about os.walk()! Will be putting this to good use!
Print('This is called details ')
when i use environ function its show none
Nice ty
THANK YOU for this tutorial
You are gold worth!
Excellent explanations and examples, thank you!
Python Tip & Tricks (2) – The Python 'import' Keyword
https://youtu.be/1opdbaOIksw
Thank you for the video. I am grateful for your time and contribution. Kind regards, Akira.
Hey I appreciate. Wat you do.
How do you use this module to rename or manipulate my files?
THANKS!
Hi Corey: I love Your work with Python. Please tell which JavaScript videos I can sart learning from. I've been studying ZTM's JavaScript Web Projects Class, but some of the JavaScript is a bit much for Me as I have never seen it before. It's way cool though and I would love to learn from you. Thanks! Rob
Great VIDEO!!!!!
the os.removedirs does it delete to recycle bin? or without recycle bin?
very informative tutorial, thanks