# Python Data Persistence – File/Directory Management Functions

## Python Data Persistence – File/Directory Management Functions

We normally use operating systemâ€™s GUI utilities or DOS commands to manage directories, copy, and move files etc. The os module provides useful functions to perform these tasks programmatically. os .mkdir ( ) function creates a new directory at given path. The path argument may be absolute or relative to the current directory. Use chdir ( ) function to set current working directory at the desired path. The getcwd ( ) function returns the current working directory path.

Example

>>> os.mkdir('mydir')
>>> os.path.abspath('mydir')
'E:\\python37\\mydir'
>>> os.chdir('mydir')
>>> os.getcwd()
'E:\\python37\\mydir'

You can remove a directory only if the given path to rmdir ( ) function is not the current working directory path, and it is empty.

Example

>>> os.chdir( ' . . ' ) #parent directory becomes current working directory
>>> os.getcwd ( )
'E:\\python37'
>>> os.rmdir('mydir')

The rename ( ) and remove ( ) functions respectively change the name of a file and delete a file. Another utility function is listdir () which returns a list object comprising of file and subdirectory names in a given path.