Python Data Presistence – os Module

Python Data Presistence – os Module

This is another module containing useful utilities for manipulating files and directories programmatically. The usual operating system commands for directory management have equivalents in this module. There is mkdir ( ) function that creates a new directory inside the current directory by default. To create it at any other location in the file system, its absolute path has to be given.

Example

import os
os.mkdir(1newdir’) # inside current directory
os.mkdir(‘c:\\newdir’) #in C drive

The chdir ( ) function (to set current working directory) and rmdir ( ) function (to remove a directory) also take relative path by default. A ge tcwd ( ) function is also available to know which is the current working directory. All these operations are demonstrated in following interpreter session:

Example

>> import os
>>> os.mkdir(“newdir”) #new directory in current path
>>> os.chdir(“newdir”) #set current directory
>>> os.getcwdO #displays current working directory
‘E:\\python37\\newdir’
>>> os.rmdir(“newdir”) #shouldn’t be current directory and should be empty Traceback (most recent call last):
File “<stdin>”, line 1, in <module> FileNotFoundError: [WinError 2] The system cannot
find the file specified: ‘newdir’
>>> os.chdir) #sets current directory to parent
directory
>>> os.getcwd ( )
‘ E:\\python3 7 ‘
>>> os.rmdir(“newdir”) #now it can be deleted
>>> os.listdirO #returns list of files and directories in current path
[‘abcdemo.py’, ‘aifftest.py’, ‘checkindent.py’,
‘clbr.py’, 1combinations-2.py’, ‘combinations.py’,
‘comprehensionl.py’, ‘conditionals.jpg’, ‘continue- example.py’, ‘data_class.py’, ‘DLLs’, ‘Doc’, ‘else- in-loop.py’, ‘ equitriangle .py’ , ‘fibolist.py’ ,
‘ findertest.py’, ‘for-l.py’, ‘for-2.py’, ‘for-3.
py’, ‘for-4.py’, ‘for-5.py’, ‘for-6.py’, ‘for-7.
py’, ‘gcexample.py’, ‘hello.py’, ‘include’, ‘Lib’,
‘libs’, ‘LICENSE.txt’, ‘modfinder.py’, ‘modspec. py’, ‘modulel.py’, ‘module2.py’, ‘mydb.sqlite3’,
‘myfunctions.cover’, ‘myfunctions.py’, ‘mymain.
cover’, ‘mymain.py’, ‘nestedfor.py’, ‘newdirbak’,
‘NEWS.txt’, ‘out.aiff’, ‘out.au’, ‘out.mp3’,
‘out.wma’, ‘polar.png’, ‘python.exe’, ‘python3. dll’, ‘python37.dll’, ‘pythonw.exe’, ‘report.txt’,
‘runpyexample.py’, ‘sample.wav’, ‘Scripts’, ‘secret- number.py’, ‘securepwd.py’, ‘sound.aiff’, ‘sound,
wav’, ‘sqrmodule.py’, ‘structexample.py’, ‘tabdemo.py’, ‘taxl.py’, ‘tax2.py’, ‘tax3.py'( ‘tax4. py’, ‘tel’, ‘testindent.py’, ‘Tools’, ‘triangle, py’, ‘trianglebrowser.py’, ‘vcruntimel40.dll’,
‘warningexample.py’, ‘wavetest.py’, ‘while-1.py’, ‘_threadexample.py’, ‘ pycache ‘]
>>>

The os module also has functions to create a new file and perform read/ write operations on it. We shall learn about these functions in the chapter on File Handling.