Flying through Directories

Python comes with a pre-defined ‘os’ module which makes crawling through your directories a very easy task. Though it will make your code depend on the end user’s operating system, the well-written documentation can really help you with the hitch.

Let’s go through some of the methods that you cannot skip while tampering around your folders –

  • os.getcwd()-It gives you the current working directory of the script. The current working directory is the directory where you are currently working on. All relative paths written are measured relative to the current working directory.
  • os.chdir(path)– change the current working directory to the path specified Example-os.chdir(‘F://Lectures//Python’) changes the current working directory to the folder ‘Python’ inside the folder ‘Lectures’ of the ‘F’ drive.
  • os.listdir(path)returns a list of all the files and folders present in the directory given by path.
  • os.mkdirs(path)- similar to os.mkdir but makes all directories required to allow the new path to exist.
  • os.remove(path)- Deletes the file path given. An error is raised if the path is a directory instead of a file.
  • os.rename(src, dst)- Renames the given file/folder. An error is raised if permissions are denied by the os.
  • os.rmdir(path)- Removes the directory tree. Only works if the given directory is empty.

Example Code-

Below lies a small piece of code that allows us to get a list of all the files and folders in a path:

def get_everything_in(self,path):
        return [d for d in os.listdir(path)]

Similarly, os.listdir can be used to get all the folder names present in a path by including an if condition as shown:

def get_folders_in(self,path):
        return [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]

All these methods form the basics of crawling through files and folders in your personal space. However, these form a very small section of the OS module which includes a large number of functions related to Process Management as well. Check all the methods of the module in the well-written documentation.


Share This