...

/

Directory and file functions in Python

Directory and file functions in Python

os module in python provides several methods to work with directories and files. We will look at some of those functions in this lesson

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:

Press + to interact
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:

Press + to interact
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 ...