How to Manipulate Directories in Python

Valento
You track variables. Now track what you’re worth.
Bring your accounts, assets, and debts together in one clear net worth view.
Get Valento for iPhone 

Summary: in this tutorial, you’ll learn how to manipulate directories in Python using the os module.

Get the current working directory #

The current working directory is the directory where the Python script is running. To get the current working directory, you use the os.getcwd() as follows:

import os


cwd = os.getcwd()
print(cwd)

To change the current working directory, you use the function os.chdir():

import os


os.chdir('/script')
cwd = os.getcwd()
print(cwd)

Join and split a path #

To make a program work across platforms including Windows, Linux, and macOS, you need to use platform-independent file and directory paths.

Python provides you with a submodule os.path that contains several useful functions and constants to join and split paths.

The join() function joins path components together and returns a path with the corresponding path separator. For example, it uses backslash () on Windows and forward slash (/) on macOS or Linux.

The split() function splits a path into components without a path separator. Here’s an example of using join() and split() functions:

import os

fp = os.path.join('temp', 'python')
print(fp)  # temppython (on Windows)

pc = os.path.split(fp)
print(pc)  # ('temp', 'python')

Test if a path is a directory #

To check if a path exists and is a directory, you can use the functions os.path.exists() and os.path.isdir() functions. For example:

import os

dir = os.path.join("C:\", "temp")
print(dir)

if os.path.exists(dir) or os.path.isdir(dir):
    print(f'The {dir} is a directory')

Create a directory #

To create a new directory, you use os.mkdir() function. And you should always check if a directory exists first before creating a new directory.

The following example creates a new directory called python under the c:temp directory.

import os

dir = os.path.join("C:\", "temp", "python")
if not os.path.exists(dir):
    os.mkdir(dir)

Rename a directory #

To rename the directory, you use the os.rename() function:

import os

oldpath = os.path.join("C:\", "temp", "python")
newpath = os.path.join("C:\", "temp", "python3")

if os.path.exists(oldpath) and not os.path.exists(newpath):
    os.rename(oldpath, newpath)
    print("'{0}' was renamed to '{1}'".format(oldpath, newpath))

Delete a directory #

To delete a directory, you use the os.rmdir() function as follows:

import os

dir = os.path.join("C:\","temp","python")
if os.path.exists(dir):
    os.rmdir(dir)
    print(dir + ' is removed.')

Traverse a directory recursively #

The os.walk() function allows you to traverse a directory recursively. The os.walk() function returns the root directory, the sub-directories, and files.

The following example shows how to print all files and directories in the c:temp directory:

import os

path = "c:\temp"
for root, dirs, files in os.walk(path):
    print("{0} has {1} files".format(root, len(files)))

Summary #

  • Use the os.getcwd() function to get the current working directory.
  • Use the os.chdir() function to change the current working directory to a new one.
  • Use the os.mkdir() function to make a new directory.
  • Use the os.rename() function to rename a directory.
  • Use the os.rmdir() function to remove a directory.
  • Use the os.walk() function to list the contents of a directory.

Quiz #

Quiz

Manipulating Directories in Python

8 questions

To help you understand how to manipulate directories in Python using the os module.

Was this helpful?