Operating System Commands

Learn about the different functions present in the operating system module.

We'll cover the following

Introduction to OS commands

Python also provides you with a module that has operating system commands. Here are some of the functions available when you import os:

  • Use os.getcwd() to get the current working directory.

  • Use os.chdir(path) to change the current working directory to path.

  • Use os.listdir(path=".") to return a list containing the names of the entries in the directory ".".

    • Note that path (not italicized) in the listdir method is a keyword, not a variable that can be replaced by some other name. In all the other functions, path (italicized) represents a variable containing a string or the string itself.
  • Use os.mkdir(path, mode=0o777, dir_fd=None) to create a directory named path with numeric mode 0o777. Here, the dir_fd is an optional parameter that is used as a unique identifier referring to a directory with None as the default value.

    The mode is a Unix-style three-digit octal code. The three bits of each digit specify read, write, and execute permissions for owner, group, and world.

  • Use os.remove(path, dir_fd=None) to delete the single file path. This is not for directories.

  • Use os.rmdir(path, dir_fd=None) to remove (delete) the empty directory path.

  • Use os.rename(src, dst) to rename the file or src directory to dst.

  • Use os.walk(top, topdown=True, onerror=None, followlinks=False) to generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at the top directory (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

Here’s an example of this :

Get hands-on with 1400+ tech skills courses.