Lesson 11: Python Standard Library: math and os

The Python Standard Library has a wide range of ready-made features provided by installing Python. You can see the full list of these features at (Python 2x) and (Python 3x). It should be noted that a large part of Python’s strength is due to its many powerful libraries, many of which are being developed outside the standard Python library and within the user community, and an almost complete list of which can also be searched and downloaded by PyPI.

   

This lesson, as the last lesson from the introductory level of the book, is dedicated to examining some of the practical possibilities of this library, which, of course, we may have used during the previous lessons!

✔ Level: Introductory

Headlines

Lesson 11: Python Standard Library: math and os

math os os.path

math

This module contains constants and mathematical functions [Python documents], some of which are as follows:

>>> import math
>>> math.pi
3.141592653589793
>>>
>>> import math
>>> math.e
2.718281828459045
>>>
  • math.inf: (from version 3.5 onwards) – A constant containing a positive value of infinity, which is equal to the output of the function float (‘ inf). math.inf – is also equal to a negative infinity) [Python Documents] .

To check if inf (positive or negative) uses the function math.isinf (x) [Python documents]:

>>> import math
>>> a = math.inf
>>> b = 10
>>> a > b
True
>>> math.inf + math.inf
inf
>>> 1 / math.inf
0.0
>>> math.inf / 2
inf
>>> 3 * math.inf
inf
>>> -3 * math.inf
-inf
>>> math.isinf(a)
True
>>> math.isinf(b)
False
>>>
  • math.nan: From version 3.5 onwards – a constant containing the value “undefined” or NaN – abbreviated Not a Number (Wikipedia) – which is equal to the output of the function float (‘nan) [Python documents].

To check for nan, the function math.isnan (x) [Python documents] is used:

>>> import math
>>> a = math.nan
>>> a
nan
>>> 0 * math.inf
nan
>>> math.inf - math.inf
nan
>>> math.isnan(a)
True
>>>
  • math.ceil (x): Returns the smallest integer greater than or equal to (x) [Python Documents]:
>>> import math
>>> math.ceil(4)
4
>>> math.ceil(-4.17)
-4
>>> math.ceil(4.17)
5
>>>
  • math.floor (x): Returns the largest integer less than or equal to x [Python Documents]:
>>> import math
>>> math.floor(4)
4
>>> math.floor(-4.17)
-5
>>> math.floor(4.17)
4
>>>
>>> import math
>>> math.fabs(-4.17)
4.17
>>> math.fabs(-4)
4.0
>>> math.fabs(4)
4.0
>>>
>>> import math
>>> math.factorial(5)
120
>>>
>>> import math
>>> math.exp(3)
20.085536923187668
>>>
  • math.log (x [, base]): Returns the logarithm of x at base base; the base argument is optional, and if not mentioned, by default the logarithm of x is at base e, or the natural logarithm (Wikipedia) Returns [Python Documents]:
>>> import math
>>> math.log(math.e) # ln e == 1
1.0
>>> math.log(1) # ln 1 == 0
0.0
>>>
>>> math.log(8, 2) # 2**3 == 8
3.0
>>> math.log(100, 10) # 10**2 == 100
2.0
>>> math.log(81, 3) # 3**4 == 81
4.0
>>> math.log(2, 10)
0.30102999566398114
>>>

For ease of use in mathematical calculations, two functions log10 (x) [Python documents] – calculate the logarithm of the number x at the base of the number 10 – and) log2 (x) [Python documents] – calculate the logarithm of the number x at the base of the number 2; Next Added – Also Available:

>>> math.log10(100)
2.0
>>> math.log2(8)
3.0
>>>
>>> import math
>>> math.sqrt(4)
2.0
>>>
  • math.pow (x, y): returns x to the power of y and returns the result [Python Documents]:
>>> import math
>>> math.pow(3, 2)
9.0

This function converts both arguments to float; If you want to work with integers, use the ** operator or the pow () function [Python Documents]:

>>> 3**2
9
>>> pow(3, 2)
9
  • Trigonometric functions: Python documents: cos (x), sin, x, tan, x, acos, x, asin, x, and atan, all of which have angles x in radians:
>>> import math
>>> math.cos(0)
1.0
>>> math.sin(0)
0.0
>>> math.tan(0)
0.0
>>>
  • math.degrees (x): Converts the angle x from radians to degrees [Python Documents]:
>>> import math
>>> math.degrees(0)
0.0
  • math.radians (x): converts x angle from degrees to radians [Python Documents]:
>>> import math
>>> math.degrees(0)
0.0
>>> math.radians(30)
0.5235987755982988
>>> math.sin(math.radians(90))
1.0

Hyperbolic functions [Python documents]: cosh (x) and (sinh) x and tanh (x) and (acosh) x and asinh (x) and atanh (x).

os

This module allows you to use some of the capabilities of the operating system; Like getting the path to the program directory [Python Documents]. Some of the functions in this module are as follows:

  • os.environ: An object of the mapping type – such as the dictionary type [see Lesson 8] – that contains the operating system environment variables [Python Documents]

It should be noted that the value of this command corresponds to the moment from the operating system when the OS module was imported into the script and does not include variables that are created after this moment.

>>> # Python 3.x, GNU/Linux
>>> import os
>>> os.environ
environ({'LOGNAME': 'saeid', 'PWD': '/home/saeid', '_':
'/usr/bin/python3', 'LANG': 'en_US.UTF-8', 'PATH':
'/usr/local/sbin:/usr/local/bin:/usr/bin', 'ZSH':
'/home/saeid/.oh-my-zsh'})
>>>
>>> os.environ['PATH']
'/usr/local/sbin:/usr/local/bin:/usr/bin'
>>> os.environ['LANG']
'en_US.UTF-8'
  • () os.getcwd: Returns the current Working Directory path. The output of this function is equal to the pwd command on the Gnolinux command line or% echo% CD on the Windows command line. [Python Documents]:
# Python 3.x, GNU/Linux
~ pwd
/home/saeid
~ python3 -q
>>> import os
>>> os.getcwd()
'/home/saeid'
>>>
  • os.chdir(path): changes the path of the current directory to the path of the received path argument. The function of this function is equal to the cd command in the command line of Gnolinux and Windows. [Python documents]:
>>> import os
>>> os.getcwd()
'/home/saeid'
>>> os.chdir('/etc')
>>> os.getcwd()
'/etc'
  • os.listdir (path): Returns a list object that contains the contents of the path directory. If the path argument is not sent, the current directory path is considered by default. [Python Documents]
>>> import os
>>> os.listdir('/home/saeid/Pictures')
['scan0001.jpg', 'smplayer_screenshots', 'GNU.png',
'Wallpapers']
  • os.mkdir (path): Creates a directory whose full name is specified by the path argument. If this directory already exists, a FileExistsError exception occurs. [Python Documents]:
>>> import os
>>> os.mkdir('dir1')

In the example code above, since the directory path is not specified; The dir1 directory is created by default on the current directory path (here: / home / saeid /); This causes an exception by executing the following command:

>>> os.mkdir('/home/saeid/dir1')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: '/home/saeid/dir1'
>>> os.mkdir('/home/saeid/Documents/dir2')

The above code instance creates the dir2 directory within the Documents directory path.

The directory path must be entered correctly; In the example of the code below, an exception occurred because there is no dir3 directory.

>>> os.mkdir('/home/saeid/Documents/dir3/dir4')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory:
'/home/saeid/Documents/dir3/dir4'
  • os.makedirs (path): is the same as os.mkdir (path) but with the difference that it also creates all the required intermediate directories. [Python Documents]

In the example of the code below to create the dir5 directory, the dir3 and dir4 directories, which do not exist, are also created.

>>> import os
>>> os.makedirs('/home/saeid/Documents/dir3/dir4/dir5')
  • os.rmdir (path): Removes the directory specified by the path argument. This directory must be empty, otherwise an OSError exception occurs. [Python Documents]
  • Of course, to completely delete a directory with all its contents, you can use the rmtree (path) function inside the shutil module [Python documents]:
>>> import shutil
>>> shutil.rmtree("/home/saeid/Documents/dir1")
  • os.removedirs (path): is the same as (os.rmdir) path, except that it has a recursive function and deletes the directories specified in the path argument one by one until an error occurs. [Python Documents]
>>> import os
>>> os.removedirs('/home/dir1/dir2/dir3')

In the example code above, the dir3 directory (with the path ‘home / dir1 / dir2 / dir3 /’) is deleted first – if it is empty – and then attempts to delete the dir2 directory (with the path ‘home / dir1 / dir2 /’) It is possible that if it is empty and deleted, the removal process will continue in the same way for the rest of the route.

  • os.rename (src, dst): This function is used to rename a file or directory. The src argument is the original name and the dst argument is the new name for the file or directory [Python Documents]:
>>> import os
>>> os.getcwd()
'/home/saeid/Documents/dir'
>>> os.listdir(os.getcwd())
['fontsdir', 'index.html', 'style.css']
>>> os.rename("fontsdir", "_fonts")
>>> os.listdir(os.getcwd())
['index.html', 'style.css', '_fonts']

Note that if the file or directory is in a different direction from the directory path; It is necessary to mention the name in full (along with the route). It is also obvious that changing the path in the dst argument causes the Move action:

>>> import os
>>> os.getcwd()
'/home/saeid/Documents/dir/dir1'
>>> os.listdir(os.getcwd())
['index.html', 'style.css', '_fonts']
>>> os.rename("_fonts", "/home/saeid/Documents/dir/dir2/_
fonts")
>>> os.listdir(os.getcwd())
['index.html', 'style.css']
>>> os.chdir('/home/saeid/Documents/dir/dir2')
>>> os.listdir(os.getcwd())
['_fonts']

In Gnolinux, if you want to change the file name to a pre-existing name, ‌ [if the user also has permission to access (Permission)] an action is performed (Replace), but for such cases in the Windows operating system An OSError error will occur. This event causes an OSError error on both operating systems when renaming a directory.

  • os.renames (old, new): has a similar function to the rename () function, except that if the middle directories of the new argument path do not exist, it also creates them [Python documents]:
>>> import os
>>> os.getcwd()
'/home/saeid/Documents/dir'
>>> os.listdir(os.getcwd())
['index.html', 'style.css', '_fonts', 'js']
>>> os.renames("style.css", "css/style.css")
>>> os.listdir(os.getcwd())
['index.html', 'css', '_fonts', 'js']
  • os.walk (rootdirpath): Routes the path of a directory as a root directory) and returns the path of any directory it sees, along with the names of the directories and the files within it. [Python Documents]:
dir1
├── dir2
│   └── file21
├── file11
└── file12
>>> import os
>>> tuple(os.walk('/home/saeid/Documents/dir1'))
(('/home/saeid/Documents/dir1', ['dir2'],
['file12', 'file11']), ('/home/saeid/Documents/dir1/dir2',
[], ['file21']))
>>> import os
>>> for root, dirs, files in os.walk('/home/saeid/Documents
/dir1'):
... print('Found directory: {}'.format(root))
... for filename in files:
... print('\t{}'.format(filename))
...
Found directory: /home/saeid/Documents/dir1
 file12
 file11
Found directory: /home/saeid/Documents/dir1/dir2
 file21
>>>

To navigate directories by default is from the top (root directory) to the bottom, which can be reversed by falsifying the optional topdown argument:

>>> for root, dirs, files in os.walk('/home/saeid/Documents
/dir1', topdown=False):
... print('Found directory: {}'.format(root))
... for filename in files:
... print('\t{}'.format(filename))
...
Found directory: /home/saeid/Documents/dir1/dir2
 file21
Found directory: /home/saeid/Documents/dir1
 file12
 file11
>>>
  • os.sep: This variable contains the character that the operating system uses to separate the components of a path. Such as: / in Gnolinux or \\ in Windows [Python Documents]
  • os.extsep: This variable contains a character that is used in the current operating system to separate the file name from its extension. As: . (File name: script.py) [Python Documents]
  • os.pardir: Contains a value that is used in the current operating system to point to a directory higher than the current directory (Parent Directory). Such as: .. in Gnolinux and Windows [Python Documents]:
# GNU/Linux
~ pwd
/home/saeid/Documents
~ cd ..
~ pwd
/home/saeid
  • os.curdir: Contains the value used in the current operating system to refer to the current directory (Current Directory). As: . In Gnolinux and Windows [Python Documents]:
# GNU/Linux
~ pwd
/home/saeid
~ cd .
~ pwd
/home/saeid
~ cd ./..
~ pwd
/home

os.path

This module implements useful functions for working with file paths and directories [Python Documents].

consideration Use open () to read and write files and os module to access the file system.

  • os.path.split (path): parses the received path path into a tuple (dirname, basename) in which the basename will be the last part of the path and dirname path whatever it is before the basename [Python Documents]:
>>> import os.path
>>> for path in [ '/one/two/three',
... '/one/two/three/',
... '/',
... '.',
... '']:
... print ('"%s" : "%s"' % (path, os.path.split(path)))
...
"/one/two/three" : "('/one/two', 'three')"
"/one/two/three/" : "('/one/two/three', '')"
"/" : "('/', '')"
"." : "('', '.')"
"" : "('', '')"
>>>
  • os.path.basename (path): Returns a value equal to the second part of the function output output (os.path.split) path [Python Documents]:
>>> import os.path
>>>
>>> for path in [ '/one/two/three',
... '/one/two/three/',
... '/',
... '.',
... '']:
... print ('"%s" : "%s"' % (path, os.path.basename(path)))
...
"/one/two/three" : "three"
"/one/two/three/" : ""
"/" : ""
"." : "."
"" : ""
>>>
  • os.path.dirname (path): Returns a value equal to the first part of the function output (os.path.split) path [Python Documents]:
>>> import os.path
>>>
>>> for path in [ '/one/two/three',
... '/one/two/three/',
... '/',
... '.',
... '']:
... print ('"%s" : "%s"' % (path, os.path.dirname(path)))
...
"/one/two/three" : "/one/two"
"/one/two/three/" : "/one/two/three"
"/" : "/"
"." : ""
"" : ""
>>>
  • os.path.splitext (path): is similar to the function (os.path.split) path except that it separates the suffix from the path and returns the result as a tuple [Python Documents]:
>>> import os.path
>>>
>>> for path in [ 'filename.txt',
... 'filename',
... '/path/to/filename.txt',
... '/',
... '.',
... '']:
... print ('"%s" : "%s"' % (path, os.path.splitext(path)))
...
"filename.txt" : "('filename', '.txt')"
"filename" : "('filename', '')"
"/path/to/filename.txt" : "('/path/to/filename', '.txt')"
"/" : "('/', '')"
"." : "('.', '')"
"" : "('', '')"
>>>
# GNU/Linux
import os
>>> os.path.join('one', 'two', 'three')
'one/two/three'
>>> os.path.join(os.sep, 'one', 'two', 'three')
'/one/two/three'
# Windows
import os
>>> os.path.join('one', 'two', 'three')
'one\\two\\three'
>>> os.path.join(os.sep, 'one', 'two', 'three')
'\\one\\two\\three'

Also, to create multiple paths at the same time, you can put the components of each path in a list (or list) inside a list and then use the for loop to send the components of each path separately to the join function. Of course, it should be noted that the parameter specified in the definition of the join function must be specified with an asterisk; In this case, the components within a tuple (or list) are considered as separate parameters of the function.

>>> import os
>>> for parts in [ ('one', 'two', 'three'),
... ('/', 'one', 'two', 'three'),
... ('/one', 'two', '/three', 'four'),
... ]:
... print (parts, ':', os.path.join(*parts))
...
('one', 'two', 'three') : one/two/three
('/', 'one', 'two', 'three') : /one/two/three
('/one', 'two', '/three', 'four') : '/three/four'
>>>

Attention Each path must contain exactly one directory separator character (os.sep) otherwise the components will only be considered from the last instance onwards. This happened in the third toplet (‘one’, ‘two’, ‘/ three’, ‘four /’) of the above code example.

  • os.path.expanduser (path): This function accepts only one parameter with the user combination and converts the ~ character to the user’s directory in the operating system [Python Documents]:
# GNU/Linux
>>> os.path.expanduser('~saeid')
'/home/saeid'
# Windows
>>> os.path.expanduser('~saeid')
'C:\\Documents and Settings\\saeid'
# GNU/Linux
>>> for user in [ '', 'saeid', 'www-data', 'postgres' ]:
... lookup = '~' + user
... print (lookup, ':', os.path.expanduser(lookup))
...
~ : /home/saeid
~saeid : /home/saeid
~www-data : /var/www
~postgres : /var/lib/postgresql
>>>
  • os.path.expandvars (path): This function replaces the value of the environmental variables in the received parameter and returns the result. The names of the variables must be indicated by the name $ pattern inside the parameter. [Python Documents]:
>>> import os
>>> os.environ['MYVAR'] = 'VALUE'
>>> os.path.expandvars('/path/to/$MYVAR')
'/path/to/VALUE'
  • os.path.normpath (path): normalizes the path. In this way, all paths that are in one of the forms A // BA / B / A /./ BA / foo /../ B, in the form of A / B Also converts the Gnolinux (/) directory character separator to \ in the Windows operating system [Python Documents]:
>>> for path in [ 'one//two//three',
... 'one/./two/./three',
... 'one/../one/two/three',
... ]:
... print (path, ':', os.path.normpath(path))
...
one//two//three : one/two/three
one/./two/./three : one/two/three
one/../one/two/three : one/two/three
>>>
# Windows
>>> for path in [ 'one/two/three',
...
... 'one\\two\\three',
... 'one\\.\\two\\.\\three',
... 'one\\..\\one\\two\\three',
... ]:
... print (path, ':', os.path.normpath(path))
...
one/two/three : one\two\three
one\two\three : one\two\three
one\.\two\.\three : one\two\three
one\..\one\two\three : one\two\three
  • os.path.abspath (path): normalize the relative path to the absolute path The result of this function is equal to the result of os.path.normpath (os.path.join (os.getcwd (), path)). [Python Documents]:
>>> import os
>>> os.getcwd()
'/mnt/Data/WorkSpace/PythonPersianTutorial'
>>> for path in [ '.',
... '..',
... './one/two/three',
... '../one/two/three']:
... print ('"%s" : "%s"' % (path, os.path.abspath(path)))
...
"." : "/mnt/Data/WorkSpace/PythonPersianTutorial"
".." : "/mnt/Data/WorkSpace"
"./one/two/three" : "/mnt/Data/WorkSpace
/PythonPersianTutorial/one/two/three"
"../one/two/three" : "/mnt/Data/WorkSpace/one/two/three"
>>>
# Windows
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> for path in [ '.',
... '..',
... './one/two/three',
... '../one/two/three']:
... print ('"%s" : "%s"' % (path, os.path.abspath(path)))
...
"." : "C:\Python34"
".." : "C:\"
"./one/two/three" : "C:\Python34\one\two\three"
"../one/two/three" : "C:\one\two\three"
>>>
  • Sometimes it is necessary to check whether a path is related to a file or a directory or a symbolic link (Symbolic link), is an absolute path (Absolute) or not, does not exist at all, etc. For this purpose, you can use the following functions used:

isabs (path): True returns if path is absolute [Python Documents] isfile (path): Returns True if the path to a file that already exists. This function also tracks links to files, so this function can return a True value for a specific path along with the islink function. [Python Documents] isdir (path): Returns True if the path to a directory that already exists. This function also follows links to directories, so this function can return a True value for a specific path along with the islink function. [Python Documents] islink (path): True returns if the path is related to a symbolic link. [Python Documents] exists (path): True returns if the received path exists regardless of whether it belongs to a file or a directory. [Python Documents] lexists (path): True returns if the received symbolic link path is available. This function does not follow the link and does not check if the link is safe. [Python Documents]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Python 3.x
# File Name: file_script.py
import os
for path in [ __file__, os.path.dirname(__file__), '/', '/var/www/html/wordpress']:
 print ('Path :', path)
 print ('Absolute :', os.path.isabs(path))
 print ('Is File? :', os.path.isfile(path))
 print ('Is Directory? :', os.path.isdir(path))
 print ('Is Link? :', os.path.islink(path))
 print ('Is Mount point? :', os.path.ismount(path))
 print ('Exists? :', os.path.exists(path))
 print ('Link Exists? :', os.path.lexists(path))
 print ()
Path : /home/saeid/Desktop/file_script.py
Absolute : True
Is File? : True
Is Directory? : False
Is Link? : False
Is Mount point? : False
Exists? : True
Link Exists? : True
Path : /home/saeid/Desktop
Absolute : True
Is File? : False
Is Directory? : True
Is Link? : False
Is Mount point? : False
Exists? : True
Link Exists? : True
Path : /
Absolute : True
Is File? : False
Is Directory? : True
Is Link? : False
Is Mount point? : True
Exists? : True
Link Exists? : True
Path : /var/www/html/wordpress
Absolute : True
Is File? : False
Is Directory? : True
Is Link? : True
Is Mount point? : False
Exists? : True
Link Exists? : True

  The __file__ variable in each script refers to the full name of that script. The fourth path in the above code example is actually a link path to another directory. 😊 I hope it was useful

 

Remember the Windows XP operating system? You can work with it online at GeekPrank.com and trick your friends.

Leave a Reply

Your email address will not be published. Required fields are marked *