How to Use the os Module in Python with Examples
The Python os module is a Swiss army knife for your operating system, giving you access to files, directories, and other operating system features in your Python code. This module acts as a bridge between your code and the proprietary way your os handles its file system. It’s also a portable module, meaning you can use the same methods and get the same results whether you’re running your Python code on Windows, Mac OSX, or Linux so long as the os supports the functionality. If the operating system doesn’t support a method, an OSerror is raised.
This module has a lot of functionality. You can use it to get the path of your current directory, get the names of files and folders in that directory, change directories, delete a directory, and much more. The best way to learn what you can do with this module is through examples of real Python code, such as in the list of examples below. So open your Python IDE and try out some of these examples on your own.
Python os module methods with examples
Get the name of the operating system module imported using os.name
While you might think this attribute would tell you the name of the operating system your python code is running on, that’s not the case. Instead, it returns a string that is the name of the Python module used by the os module.
For example:
# Import the os module import os # Print the name print(os.name) # Will print “posix” on Mac and Linux and “nt” on Windows |
Last Updated July 2023
Learn Python like a Professional Start from the basics and go all the way to creating your own applications and games | By Jose Portilla
Explore CourseGet operating system details with os.uname()
To get the details about the operating system itself instead of only the Python os module in use, use the os.uname() method. It returns an object with five attributes:
- sysname – operating system name
- nodename – name of machine on network
- release – operating system release
- version – operating system version
- machine – hardware identifier
Here is an example:
# Import the os module import os # Get the uname data uname = os.uname() # Print the details print(uname) |
Here is an example of what this script will return:
posix.uname_result(sysname=’Darwin’, nodename=’MAC-000808.local’, release=’19.6.0′, version=’Darwin Kernel Version 19.6.0: Tue Oct 12 18:34:05 PDT 2021; root:xnu-6153.141.43~1/RELEASE_X86_64′, machine=’x86_64′) |
Determine what terminal you’re using with os.ctermid()
This method returns the filename of the terminal application you’re using.
Here is an example:
# Import the os module import os # Get the terminal details terminal = os.ctermid() # Print the terminal path print(terminal) |
This script will print something like “/dev/tty”.
Get all environment variables with os.environ
This os module method lists all the current environmental variables of the environment your Python code is executing in.
For example:
# Import the os module import os # Print the environment variable print(os.environ) |
The result of this script can be quite verbose depending on the amount of variables in your environment. Here is part of an example:
environ({‘TERM_PROGRAM’: ‘vscode’, ‘ANDROID_HOME’: ‘/Users/myUser/Library/Android/sdk’, ‘TERM’: ‘xterm-256color’, ‘SHELL’: ‘/bin/sh’, … |
Top courses in Python
Get a specific environment with os.getenv()
The last method can be overkill if you only need to access one or two environment variables from your Python script. With os.getenv(), you can get a specific environment variable and set a default for the value if that variable is not found.
# Import the os module import os # Get the environment variable shell = os.getenv(‘SHELL’, ‘/bin/fish’) # Print the environment variable print(shell) # If SHELL is not set, it will print /bin/fish |
Get the current working directory with os.getcwd()
The current working directory, or CWD, is the folder where Python is currently executing. When you execute a Python file by its name, without a directory path, the Python interpreter assumes the file you’re looking for is in the current working directory.
Here is a simple example using it:
# Import the os module import os # Get the current working directory cwd = os.getcwd() # Print the current working directory print(“Current working directory: {0}”.format(cwd)) |
The getcwd() function returns a string with a path to the directory you are executing the Python code, so the code above would print something like “Current working directory: /Users/myUser/Projects/python-code/”.
Change the current working directory with os.chdir()
If you wrote a Python script that processes your files, and those files are in a totally different directory, you may find this method useful. It lets you switch the current working directory to another folder.
Here is an example:
# Import the os module import os # Print the current working directory before print(os.getcwd()) # Changing the current working directory os.chdir(‘../’) # Print the current working directory after print(os.getcwd()) |
As you can see in the code above, you don’t have to specify the whole path to the file. You can also use a relative path. This code will move the current working directory up one folder, with results that look something like this:
/Users/myUser/Projects/python-code/ /Users/myUser/Projects/ |
Python students also learn
Create file paths correctly with os.path.join()
The join() method lets you join one or more paths correctly according to the os’s rules. While there is a chance you can get a path correct by writing your own function to join paths, join() works correctly on whichever operating system you’re using.
Here is an example:
# Import the os module import os # Get the current working directory cwd = os.getcwd() # Child folder in current working directory new_folder = ‘new_folder’ path = os.path.join(cwd, new_folder) # Print the directory print(“Directory ‘% s’ created” % path) |
In Mac OSX or Linux, this prints something similar to “/Users/myUser/new_folder”. In Windows, it would use backslashes and look more like “C:\Users\myUser\new_folder”.
Create a new directory with os.mkdir()
This method in Python lets you create a new directory using a specific numeric mode. If you try to create a directory that already exists, the method will raise a FileExistsError.
Here is an example:
# Import the os module import os # Get the current working directory cwd = os.getcwd() # New folder name new_folder_name = ‘new_folder’ # Create the full directory path path = os.path.join(cwd, new_folder_name) # Create the directory os.mkdir(path) print(“Directory ‘% s’ created” % path) |
The first argument that the mkdir() method accepts is the full path to the directory you will be creating. The code above joins the current working directory to the new folder name to get this value and creates a “new_folder” folder in the directory this code runs in.
The mkdir() method also accepts an optional second parameter, which is the mode the directory will be created in. Some operating systems don’t accept this value, and by default it sets to Oo777, which is readable and writable to every system. Also, if any of the directories in your path don’t exist, a FileExistsError will be raised, and the file won’t be created. In that case, you would want to use the code in the next example.
Create new directories recursively with os.makedirs()
This method works like the last except that it creates any intermediate directories that don’t exist when you’re creating a directory.
For example:
# Import the os module import os # Get the current working directory cwd = os.getcwd() # New folder path. Neither of these exist, but will be created. new_path = ‘new_folder1/new_folder2’ # Create the full directory path path = os.path.join(cwd, new_path) # Create the directory os.mkdir(path) print(“Directory ‘% s’ created” % path) |
List directories and files with os.listdir()
The os.listdir() method accepts a file path and returns a list of the files and folders in that path. The path argument is optional, and the method will list the files and folders in the current working directory if it’s not set.
Here is an example:
# Import the os module import os # Get a list of files and folders in the root directory path = “/” dir_list = os.listdir(path) # Print the list print(dir_list) |
The result of running this script looks something like this:
[‘home’, ‘usr’, ‘.DS_Store’, ‘bin’, ‘sbin’, ‘.file’, ‘etc’, ‘var’, ‘Library’, ‘System’, ‘.VolumeIcon.icns’, ‘.fseventsd’, ‘private’, ‘.vol’, ‘Users’, ‘Applications’, ‘opt’, ‘dev’, ‘Volumes’, ‘tmp’, ‘cores’] |
Featured courses in Web Development
Remove a file with os.remove()
The os.remove() method deletes a file in your operating system, but it cannot remove a directory. If you try to remove a directory with it, the method will raise an OSerror.
For example:
# Import the os module import os # Set the file name file_name = ‘my_file.txt’ # Set the directory the file is in directory = ‘/Users/myUser/Projects/python-code/’ # Create the full path path = os.path.join(directory, file_name) # Delete the file os.remove(path) |
Remove a directory with os.rmdir()
To delete a directory in Python, use os.rmdir(). This only works for empty directories. If the directory contains files or folders, the method raises an OSerror.
Here is an example:
# Import the os module import os # Set the directory to delete file_name = ‘my_directory’ # Set the parent directory path directory = ‘/Users/myUser/Projects/python-code/’ # Create the full path path = os.path.join(directory, file_name) # Delete the directory os.rmdir(path) |
Iterate the filenames in a directory with os.walk()
This method generates the filenames in a directory tree by walking the directory structure in either a top-down or bottom-up fashion. Here is the syntax for this method:
os.walk(top, topdown=True, onerror=None, followlinks=False) |
The first argument is the path where the walk starts and is the only required parameter. By default, it will do a top-down walk, and you can make this bottom-up by setting the second parameter to False. You can set the third argument to a function that will handle errors when they happen. And if you set the fourth parameter to true, it will follow symbolic links, which it doesn’t do by default. The method returns a 3-tuple with a list of directory paths, directory names, and file names.
Here is an example:
# Import the os module import os # Get the current working directory cwd = os.getcwd() # List the details for dirpath, dirnames, filenames in os.walk(cwd): print(dirpath) print(dirnames) print(filenames) |
There is a lot you can do with os.walk(). For more details, visit the official docs on the method.
Open and pipe a file or directory with os.popen()
The os.popen() method opens a pipe to or from a command. It returns an open file object connected to the pipe that can be read or written depending on what mode it was opened with. Here is the syntax for this method:
os.popen(cmd, mode=’r’, buffering=- 1) |
The default mode for opening a file is for reading. Here are the other values you can use:
- r: Opens a file for reading.
- r+: Opens a file for both reading and writing.
- w: Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, it creates a new file for writing.
- w+: Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, it creates a new file for reading and writing.
For more modes and how to use buffering, read the documentation for Python’s built-in open() method that uses the same values.
The only required parameter of os.popen() is the first one, which is the shell command you will be using for the pipe.
Here is an example:
# Import the os module import os # Open the pipe to the current working directory pipe = os.popen(‘ls -la’) # Print the results print(pipe.read()) |
Since the command used is “ls -la”, this prints the directory listing of the current working directory.
Handling errors with the os module
Because the Python os module is designed to be portable, but your operating system may not support some of the methods you’re using, you will want to use a try and accept to handle the errors that may arise.
Here is an example where we try to create recursive folders with os.mkdir(), which will not work:
# Import the os module import os # Get the current working directory cwd = os.getcwd() # Create a nested folder new_folder_name = ‘first_folder/second_folder’ # Create the full directory path path = os.path.join(cwd, new_folder_name) # Try to create the directory try: os.mkdir(path) print(“Directory ‘% s’ created” % path) except FileNotFoundError: print(‘Directory already exists’) |
Other useful methods of the Python os module
The os module is quite extensive and has more methods you can use than those used in the examples above. Here are some other methods you can use in your Python code:
- os.path.split(path): This splits a path into a head and a tail.
- os.path.dirname(path): This returns the directory name of a path.
- os.path.abspath(path): This returns the absolute version of a path.
- os.path.isfile(path): This returns true when a path points to a file and returns false when it does not.
- os.path.isdir(path): This returns true when a path points to a directory and returns false when it does not.
- os.path.exists(path): This method determines if a path exists.
To learn even more about Python, read What is Python. And if you are ready to build your Python skills, Udemy has many courses on Python you can take to learn Python at your own pace.