Logo
Unit 12 – Python Standard Library: os and sys

Python Standard Library: os and sys

Duration: 5 minutes

The Python Standard Library is a vast treasure trove of modules that provides functionalities for a wide range of tasks. In this module, we will focus on two important modules: **os** and **sys**.

The os Module

The **os** module provides a way of using operating system-dependent functionality. Here are a few important methods:- os. name: This provides the name of the operating system-dependent module imported. The following names have currently been registered: ‘posix’, ‘nt’, ‘os2’, ‘ce’, ‘java’ and ‘riscos’.

  • **os. getcwd()**: This method returns the current working directory.
  • os. listdir(): This method returns a list containing the names of the entries in the directory given by path.
  • os. mkdir(): This method creates a directory. Here’s an example of using the os module:
import os
print(os. name)  # print the name of the operating system-dependent module
print(os. getcwd())  # print the current working directory
os. mkdir('new_directory'# create a directory named 'new_directory'
print(os. listdir())  # print the list of entries in the current directory

The sys Module

The **sys** module provides access to some variables used or maintained by the Python interpreter and to functions that interact strongly with the interpreter. Here are a few important features:- **sys. argv:** This is a list in Python, which contains the command-line arguments passed to the script.

  • sys. path: This is an environment variable that is a search path for all Python modules.
  • sys. exit(): This function allows you to exit from Python. Here’s an example of using the sys module:
import sys
print(sys. argv)  # print the command-line arguments
print(sys. path)  # print the search path for all Python modules
sys. exit()  # exit from Python

Exercise

Now, your task is to create a Python script that makes use of both the **‘os’ **and **‘sys’ **modules. The script should print the Python search path, then create a new directory named ‘test_directory,’ and finally print the existing directory’s list of contents.

Conclusion

The **‘os’ **and **‘sys’ **modules are Python Standard Library integral components that enable communication with the operating system and the Python interpreter. The more you learn about these modules, the better your Python skills will grow. Continue your exploration!

Next Tutorial: Python Standard Library: Datetime and Time

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!