Search⌘ K
AI Features

Directory and file functions in Python

Explore Python's os module to manage directories and files effectively. Learn to change your current directory, create single or nested folders, remove files and directories, rename items, open files with their associated programs, and iterate through folder contents using os.walk. This lesson equips you with essential file and directory handling skills in Python.

os.chdir() and os.getcwd()

The os.chdir function allows us to change the directory that we’re currently running our Python session in. If you want to actually know what path you are currently in, then you would call os.getcwd(). Let’s try them both out:

Python 3.5
import os
print(os.getcwd())
# '/usercode'
os.chdir('/var')
print(os.getcwd())
# '/var'

The code above shows us that we started out in the Python directory by default when we run this code in IDLE. Then we change folders using os.chdir(). Finally we call os.getcwd() a second time to make sure that we changed to the folder successfully.

os.mkdir() and os.makedirs()

You might have guessed this already, but the two methods covered in this section are used for creating directories. The first one is os.mkdir(), which allows us to create a single folder. Let’s try it out:

Python 3.5
import os
os.mkdir("test")
path = r'/usercode/pytest'
os.mkdir(path)

The first line of code will create a folder named test in the current directory. The second example ...