Python Directory

Python Directories

All files are contained within directories, and Python has no problem manipulating them. The os module has several methods that help you create, delete, and change directories.

mkdir() Method

You can use the mkdir() method of the os module to create a directory within the current directory. You need to provide the method with an argument containing the name of the directory to create.

Syntax

os.mkdir("newdir")

Example

The following example creates a directory named test in the current directory:

#!/usr/bin/python3
import os

# Create a directory "test"
os.mkdir("test")

chdir() Method

You can use the chdir() method to change the current directory. The chdir() method accepts one argument, which is the name of the directory you want to set as the current directory.

Syntax

os.chdir("newdir")

Example

The following example changes to the “/home/newdir” directory –

import os

# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")

Methods for Getting the Current Working Directory

The getcwd() method displays the current working directory.

Syntax

os.getcwd()

Example

The following is an example to get the current directory:

#!/usr/bin/python3
import os

# This would give the location of the current directory
os.getcwd()

rmdir() Method

The rmdir() method is used to remove the directory passed as a parameter to the method.

Before removing a directory, all its contents should be removed first.

Syntax

os.rmdir('dirname')

Example

The following is an example to remove the “/tmp/test” directory. A fully qualified directory name is required; otherwise, it searches for the directory in the current directory.

#!/usr/bin/python3
import os

# This would remove the "/tmp/test" directory.
os.rmdir( "/tmp/test" )

Leave a Reply

Your email address will not be published. Required fields are marked *