Working with Directory

Current working directory

The directory that Python program is in is known as current working directory for that program. In order to get the current work directory you’ll need to use os module with the function getcwd() as follows:

To change the current working directory you can use function chdir(). You just pass the current working directory you want to change to as follows:

Joining and splitting path

In order to make you program working cross platform such as Windows, Linux and Unix, you need to use platform independent file and directory path.  Python provides a submodule os.path that contains several useful functions and constants to make it easier to join and split path.
The join() function joins path components together and returns a path with exact platform separator for instance in windows backslash (\) and Unix (/)
The split() function splits path into path components without path separator.
Here is an example of using  join() and split() functions:

Checking directory

In order to check a path exists in a system and a path is a directory you can use the functions exists() and isdir() in the submodule os.path as belows:

Creating and renaming and removing directory

To create a new directory you use mkdir() or makedirs() functions of os module. We should always check if directory exists first before create a new directory.  In this example, we will create a new directory called python under c:\temp directory.

To rename directory you use os.rename() function. You just need to pass the directory you want to change and the new path.

To remove directory you use function rmdir() as follows:

Traversing directory recursively

Python provides os.walk() function to allow you to traverse directory recursively. The os.walk() function returns the roots,  its sub-directories and its files. Here is example of printing all files and directories in the c:\temp directory:

  • Was this tutorial helpful ?
  • YesNo