Python OS Module Unit1
Python OS Module Unit1
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.
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.
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()
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:\\
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
import os
os.system('cls')
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‟).
To delete an environment variable, use the pop() method of os.environ or the del statement. Same as
dictionary.
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'
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.
To delete an environment variable, use the pop() method of os.environ or the del statement.
Same as dictionary.
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
Creating Variables
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).
Example
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
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:
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:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
+= 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
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result is not(x < 5 and x <
true 10)
is not Returns True if both variables are not the same x is not y
object
not in Returns True if a sequence with the specified value is not x not in y
present in the object
<< 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
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:
You can get the data type of any object by using the type() function
Example
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:
x = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
If you want to specify the data type, you can use the following constructor
functions:
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = range(6) range
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview