Python OS Module
Python OS module provides the facility to establish the interaction between the user and the
operating system. It offers many useful OS functions that are used to perform OS-based tasks and get
related information about operating system.
The OS comes under Python's standard utility modules. This module offers a portable way of
using operating system dependent functionality.
The Python OS module lets us work with the files and directories.
To work with the OS module, we need to import the OS module.
import os
There are some functions in the OS module which are given below:
os.name ()
This function provides the name of the operating system module that it imports.
Currently, it registers 'posix', 'nt', 'os2', 'ce', 'java' and 'riscos'.
Example
import os
print(os.name)
Output:
nt
os.mkdir()
The os.mkdir() function is used to create new directory. Consider the following
example.
Example
import os
os.mkdir("d:\\newdir")
It will create the new directory to the path in the string argument of the function in the D drive
named folder newdir.
os.getcwd()
It returns the current working directory(CWD) of the file.
Example
import os
print(os.getcwd())
Output:
C:\Users\Python\Desktop\ModuleOS
os.chdir()
The os module provides the chdir() function to change the current working
directory.
1. import os
2. os.chdir("d:\\")
Output:
d:\\
Deleting Directory or Files using Python
OS module proves different methods for removing directories and files in Python. These are –
Using os.remove()
Using os.rmdir()
Using os.remove()
os.remove() method in Python is used to remove or delete a file path. This method can not
remove or delete a directory. If the specified path is a directory then OSError will be raised by the
method.
2.os.rmdir()
The rmdir() function removes the specified directory with an absolute or related path. First,
we have to change the current working directory and remove the folder.
Example
import os
It will throw a Permission error; that's why we have to change the current working directory.
os.rmdir("d:\\newdir")
os.chdir("..")
os.rmdir("newdir")
How to clear screen in python?
Most of the time, while working with Python interactive shell/terminal (not a console), we
end up with a messy output and want to clear the screen for some reason. In an interactive
shell/terminal, we can simply use
ctrl+l
But, what if we want to clear the screen while running a python script? Unfortunately,
there‟s no built-in keyword or function/method to clear the screen. So, we do it on our own.
Clearing Screen in windows Operating System
Method 1: Clear screen in Python using cls
You can simply “cls” to clear the screen in windows.
Python3
import os
# Clearing the Screen
os.system('cls')
Example 2: Clear screen in Python using clear
You can also only “import os” instead of “from os import system” but with that, you have to
change system(„clear‟) to os.system(„clear‟).
Remove environment variables
To delete an environment variable, use the pop() method of os.environ or the del statement. Same as
dictionary.
The following is an example of pop().
pop() returns the value of the environment variable that was deleted. By default, specifying an
environment variable that does not exist will result in an error (KeyError), but specifying the second
argument will return the value of the environment variable if it does not exist.
print(os.environ.pop('NEW_KEY'))
# 100
# print(os.environ.pop('NEW_KEY'))
# KeyError: 'NEW_KEY'
print(os.environ.pop('NEW_KEY', None))
# None
The following is an example of del.
The environment variable is added again, and then deleted. If the environment variable does
not exist, an error (KeyError).
os.environ['NEW_KEY'] = '100'
print(os.getenv('NEW_KEY'))
# 100
del os.environ['NEW_KEY']
print(os.getenv('NEW_KEY'))
# None
# del os.environ['NEW_KEY']
# KeyError: 'NEW_KEY'
The following is an example of pop().
pop() returns the value of the environment variable that was deleted. By default, specifying an
environment variable that does not exist will result in an error (KeyError), but specifying the second
argument will return the value of the environment variable if it does not exist.
Remove environment variables
To delete an environment variable, use the pop() method of os.environ or the del statement.
Same as dictionary.
The following is an example of pop().
pop() returns the value of the environment variable that was deleted. By default, specifying an
environment variable that does not exist will result in an error (KeyError), but specifying the second
argument will return the value of the environment variable if it does not exist.
Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
x=5
y = "John"
print(x)
print(y)
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
A variable name cannot be any of the Python keywords.
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Python Assignment Operators
Assignment operators are used to assign values to variables:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Python Comparison Operators
Comparison operators are used to compare two values:
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Python Logical Operators
Logical operators are used to combine conditional statements:
Operator
Operator Description
Description Example
Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is not(x < 5 and x <
true 10)
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they
are actually the same object, with the same memory location:
Operator Description Example
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same x is not y
object
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
in Returns True if a sequence with the specified value is present x in y
in the object
not in Returns True if a sequence with the specified value is not x not in y
present in the object
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Name Description Example
& AND Sets each bit to 1 if both bits are 1 x&y
| OR Sets each bit to 1 if one of two bits is 1 x|y
^ XOR Sets each bit to 1 if only one of two bits is 1 x^y
~ NOT Inverts all the bits ~x
<< Zero fill left Shift left by pushing zeros in from the right and let x << 2
shift the leftmost bits fall off
>> Signed Shift right by pushing copies of the leftmost bit in x >> 2
right shift from the left, and let the rightmost bits fall off
Data types and its associated operations
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType
Getting the Data Type
You can get the data type of any object by using the type() function
Example
Print the data type of the variable x:
x = 5
print(type(x))
output
<class 'int'>
Setting the Data Type
In Python, the data type is set when you assign a value to a variable:
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
Setting the Specific Data Type
If you want to specify the data type, you can use the following constructor
functions:
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview