Directory in Python and its methods

Directory in Python and its methods

Directories

Directories are holding all python files and directories.To manipulate this directories OS Module needs to be imported.This module consists of many methods to handle directories.

List of some directory functions:

    getcwd()
    mkdir()
    chdir()
    rmdir()
    listdir()
    rename()

getcwd():

This method is used to show Current Working Directory.
To use this method,first we have to import OS module.
Syntax :

os.getcwd()

This will display the name/path of the directory in which you are working currently.

mkdir():

This method is used to make a new directory/folder in current working directory.
To use this method,first we have to import OS module.
Syntax :

os.mkdir(dir_name)

This will create a new directory in current working directory.”dir_name” can be any name given to new directory

chdir():

This method is used to change current working directory.
To use this method,first we have to import OS module.
Syntax :

os.chdir(dir_name)
>>> import os
>>> os.chdir("C:\Python34\SYIT2020")
>>>

This will change current working directory to new directory.”dir_name” can be name of directory you wish to work in.

rmdir():

This method is used to remove any directory which user wants to delete.
To use this method,first we have to import OS module.
Syntax :

os.rmdir(dir_name)

This will remove directory whose name is passed as argument.”dir_name” can be name of directory you wants delete.

listdir():

This method is used to list all directory names present in current working directory(CWD).
To use this method,first we have to import OS module.
Syntax :

os.listdir()

This will list all directories in CWD.

rename(old_dir,new_dir):

This method is used to change the name of existing directory.
To use this method,first we have to import OS module.
Syntax :

os.rename(old_dir,new_dir)

This will give new name to existing directory.
Example :

"""
Author : ITVoyagers (https://itvoyagers.in/)


Date :23rd December 2018

Description : Program to show use of directory methods
"""

>>> import os
>>> os.getcwd()                                 #used to get current working directory
'C:\Python34'                                  #o/p
>>> os.mkdir("december.txt")                    #makes new dir
>>> os.chdir("december.txt")                    #changes dir to new path
>>> os.getcwd()
'C:\Python34\december.txt'                    #o/p
>>> os.mkdir("happy.txt")
>>> os.listdir()                                #lists all directories  in CWD
['happy.txt']
>>> os.rename("happy.txt","newyear.txt")        #renames existing directories
>>> os.listdir()
['newyear.txt']
os.rmdir("newyear.txt")                         #removes existing directories
>>> os.listdir()
[]                                              #final o/p

Leave a Comment