i

Python Programming

Python Directory Methods

Files are contained within various directories,  Python has no problem handling these too and OS module got several methods that help create/remove/change directories.

The mkdir()-Method

It can use the mkdir() method of the os module to create directories in the current directory. You need to supply the argument to this method which contains the name of directory to be created.

Syntax                                    >>os.mkdir("newdir")

Example

Below is the example:

The chdir()-Method

For this we use the chdir() method to change current directory. The chdir() method takes argument which is the name of the directory that you want to make the current directory.x

Syntax                        >>os.chdir("newdir")

Example

Below is the example to go into "/home/newdir" directory −

The getcwd()-Method

The getcwd() method displays current working directory.

Syntax                                    >>>>os.getcwd()

Example

Below shows example:

rmdir()-Method

The rmdir()-method deletes the directory, which is passed as argument in method. Before removing directory, all the contents in it should be removed.

Syntax                        >>>>os.rmdir('dirname')

Example

Below is example how to remove "/tmp/test" directory.