30 Useful Methods from python OS Module

saagara Last Updated : 22 Oct, 2024
6 min read

This article was published as a part of the Data Science Blogathon.

Introduction

Many times when we work in python there are instances where we would like to utilise the functionalities of the underlying operating system. The python os module makes this possible, it provides a means for us to interact with the underlying operating system in many different ways and provides us with a portable way to use the operating system dependent functionalities.

For example, it makes it possible for us to get the path of the directory we are working with, get the names of all the files and folders within a directory, make a new directory or remove an existing one and so on.

In this blog let us explore some useful methods in the os module that can come in handy when you work on your next project.

Before getting started let us look at some of the things we need to take note of about the os module 

The design of all built-in operating system dependent modules of Python is such that as long as the same functionality is available, it uses the same interface.

Extensions peculiar to a particular operating system are also available through the os module but using them is inevitably a threat to portability.

All functions accepting path or file names accept both bytes and string objects as input , and  if a path or file name is returned then the result is also an object of the same type.

All functions in the python os module raise the OSError (or subclasses thereof) when invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system are encountered.

Let us start by importing the module

import os module

Now let’s go through the methods one by one 

1.  os.name :

import os
print(os.name)

2.  os.error :

It is the environment error class for I/O and OSError. It is raised when any function           returns any system related error

3.  os.uname() :

Gives the system dependent version information

4. os.ctermid() :

This method returns the filename corresponding to the controlling terminal of the process

os module ctermid

5. os.environ :

It is a mapping object that represents the string environment. This mapping is captured when the os module is initially imported and the changes made thereafter in the environment is not reflected except for the ones that are made by directly modifying os.environ .

6. os.environb :

It is a mapping object that represents the environment as byte strings. It is actually the Bytes version of os.environ. os.environ and os.environb are synchronised. It is available if and only if supports_bytes_environ is True.

7. os.getenv(key,default=None) :

This method returns the value of the environment variable key if it exists and if it does not exist then the default value is returned.

8. os.getcwd() :

This method returns the location of the current working directory (CWD). The CWD is the folder in which the python script is operating.

getcwd

9. os.listdir() :

This method returns a list of all the files and folders present inside the specified directory. If no directory is specified then the list of files and folders inside the CWD is returned.

os module listdir

10. os.chdir() :

It is used for changing the CWD. It changes CWD to the specified path.

os module getcwd

11. os.mkdir() :

This method creates a new directory according to the specified path. In case the specified directory already exists a FileExistsError is raised.

12. os.makedirs() :

This method creates a directory recursively. It means that while creating a leaf directory if any of the intermediate level directories specified in the path is missing then the method creates them all.

13. os.remove() :

This method deletes a file path. It cannot delete a directory. In case the specified path is that of a directory then the OSError is raised.

14. os.rmdir() :

This method is used for deleting an empty directory. If the path does not correspond to an empty directory then OSError is raised.

15. os.walk() :

This method generates the filenames in a directory tree by walking the tree in either a top-down or bottom-up manner. os.walk returns a generator that creates a tuple of values (dirpath, dirnames, filenames)

os walk

16. os.path.join() :

This method joins various path components with exactly one directory separator (“/”) following each non-empty part except for the last path component. If the last path component is empty then a directory separator (“/”) is put at the end. This method returns a string with the concatenated path.

os join

17. os.path.basename() :

This method is used to get the base name in a specified path. The method returns a string value that represents the base name of the specified path.

os path

18. os.path.split() :

This method splits the pathname into a pair of head and tail. Here, the tail is the last pathname component and the head is everything that comes before it. The method returns a tuple of the head and tail of the specified path.

os module path split

19. os.path.dirname() :

This method returns the directory name from the path given.

dirname

 

20. os.path.commonprefix() :

This method returns the longest path prefix which is a prefix for all the paths in the specified list.

os module commonprefix

21. os.path.getmtime() :

This method returns the time of the last modification of the path.

os gettime

22. os.path.getatime() :

This method returns the time of the last access of the path.

os module getatime

23. os.path.getctime() :

This method returns the ctime which is the time of the last change(Unix) or time of creation(Windows) depending on the system.

getctime

24. os.path.abspath() :

This method returns a normalised absolute version of the specified path.

25. os.path.normpath() :

This method normalises the specified path name by collapsing redundant separators and up-level references.

normpath

 

26. os.path.normcase() :

This method normalises the case of the specified pathname.

27. os.path.isfile() :

This method checks whether the specified path corresponds to an existing file or not. This method returns a boolean value.

os module isfile

28. os.path.isdir() :

This methods checks and reports whether the specified pathname corresponds to an existing directory or not. The method returns a boolean value.

os module isdir

 

29. os.path.isabs() :

This method specifies whether the given path is absolute or not.

isabs

30. os.path.exists() :

This method returns True for existing paths. It returns False for broken symbolic links.

exists

The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion. 

Responses From Readers

Clear

Dr M Abdul Rahman
Dr M Abdul Rahman

Well written and effective presentation. Even useful for beginners. Great.

Deepika P S
Deepika P S

Very clear and concise. Thanks for writing this!

Maya
Maya

Wonderful article ...very well articulated ...thankyou

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details