OS module in python

Previous
Next

OS module:

  • OS module mainly used to perform file and directory operations
  • Creating files and Directories
  • File and Directory deletions.
  • Renaming the files and directories
  • OS command execution.

getcwd():

  • “cwd” represents “Current Working Directory”
  • It is source files location.
  • It is used to find the source files location.
import os
info = os.getcwd()
print(info)

Open a file:

  • We use open() function to open file in different modes.
  • os module popen() function also working like open() function.
import os
path = "abc.txt"
mode = "w"
try:
    file = os.popen(path,mode)
    file.write("It is popen() program")
    print("Content written")

except Exception as e:
    print("Exception :",e)

Create directory:

import os
path = "d:/abc"
try:
    os.mkdir(path)
    print("Directory created...")
except Exception as e:
    print("Exception :",e)

Remove directory:

import os
path = "d:/abc"
try:
    os.rmdir(path)
    print("Directory removed..")
except Exception as e:
    print("Exception :",e)

Creating sub directories: makedirs() is used to create sub directories.

Removing sub directories: removedirs() is used to remove sub directories.

Path specification:

In Windows:
   path = "d:/abc/xyz"
In Mac:
   path = "d:\abc\xyz"

Note: Python is OS independent; we need to specify the path that should be executed on any platform.

In any OS : 

path = "d://abc//xyz"
   or
path = "d:\\abc\\xyz"
import os
path = "d:/abc/xyz/lmn"
try:
    os.makedirs(path)
    print("Directories created.")
except Exception as e:
    print("Exception :",e)

Error Code: Invalid path

import os
path = "e:\abc\xyz\lmn"
try:
    os.makedirs(path)
    print("Directories created.")
except Exception as e:
    print("Exception :",e)

system():

  • A function belongs to OS module.
  • It is used to execute a system command.
import os
os.system("notepad")
os.system("mspaint")
Previous
Next

Add Comment

Courses Enquiry Form