OS Module in Python
In this blog i will demonstrate functionalities of os module in python.
Example 1: Find current working directory
import pathlib
a=pathlib.Path.cwd()
print(a)
print(type(a))
So in this example we can clearly see that pathlib.Path.cwd() returns an object of “pathlib.WindowsPath” then one questions arises then why output for print(a) is a string containing current working path, so reason behind that is the __str__ method of class pathlib.WindowsPath got called when print(a) line got executed.
Example 2: Changing current working directory
import pathlib
import os
k=pathlib.Path.cwd()
print(k)
print(“After changing current directory, now current directory is: “,end=””)
pth=pathlib.Path(“/work/python”)
os.chdir(pth) #used to change working directory and it takes pathlib.Path as argument
print(pathlib.Path.cwd())
In this example we used method os.chdir() which is used to change current directory for the application that means till the execution of the application gets done the current working directory will be changed to the respective path which is passed as an argument to the method.
In example firstly current working directory was C:\Work\Python\Codes\FileSystem but after changing to given path the current working directory got changed to C:\Work\Python
Example 3: Creating a directory
import pathlib
import os
pth=pathlib.Path(os.getcwd())
os.chdir(pth)
path=pathlib.Path(“Hello World”)
path.mkdir()
So in this example, i used function path.mkdir() to create a folder at current working directory named as Hello World, in above picture you can cleary see that Hello World named folder was created after i executed my python script.