Python Tutorial: OS Module - Use Underlying Operating System Functionality

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
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
Info
Channel: Corey Schafer
Views: 625,966
Rating: 4.9649296 out of 5
Keywords: Python, os, os module, Python os, Python os module, import os, Python import os, Python Tutorial, Python Tutorials, os tutorial, os module tutorial, Python os tutorial, Python os module tutorial, Learn Python, Python Standard Library, Python Built In, Python Built-In, Python for Beginners, Programming Tutorials, Software Engineering, Python Path, Python os.path, os.path, os path, Python os path, os path module, os.path module
Id: tJxcKyFMTGo
Channel Id: undefined
Length: 19min 13sec (1153 seconds)
Published: Wed Apr 06 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.