Directories

To wrap up, let’s cover some useful Python tools for working with directories and files, which is especially helpful when dealing with real data stored in folders.

Python’s built-in os module includes many utilities to help with this.


Listing Directory Contents

You can list the contents of a directory using:

$ python3
>>> import os

>>> os.listdir(".")  # listdir(name_of_directory) lists the directory
['FOLDER1', 'abc.txt', 'FOLDER2']  # Returns the directory names in a list

  • "." The single dot refers to the current directory.
  • ".." Two dots would refer to the parent directory.

If you want to filter just the folders, you can use a list comprehension:

>>>  [f for f in os.listdir() if os.path.isdir(f)]
 ['FOLDER1', 'FOLDER2']


Creating a Directory

To create a new directory:

>>>  os.mkdir("FOLDER_NAME")


Changing the Current Directory

You can change the working directory (the directory in which your script is currently operating):

>>>  os.chdir('FOLDER_NAME')  # Move into a sub-directory
>>>  os.chdir('..')  # Move up to the parent directory

Everything your code does, such as reading/writing files and creating folders, happens relative to the current working directory.


Understanding Where You Are

If you want to check your current directory at any point in your script:

>>>  os.chdir('FOLDER_NAME')
>>>  print(os.getcwd())
C:\Users\rzon\FOLDER
  • Note: The slashes (forward or backward) are different for Windows, Macs, and Linux.

★ Knowledge Check
You have completed 0% of the lesson
0%