OS Interaction with OS Library

The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality. The os and os.path modules include many functions to interact with the file system.

Handling the Current Working Directory

Consider Current Working Directory(CWD) as a folder, where the Python is operating. Whenever the files are called only by their name, Python assumes that it starts in the CWD which means that name-only reference will be successful only if the file is in the Python’s CWD.

The folder where the Python script is running is known as the Current Directory. This is not the path where the Python script is located.

import os

# current working directory
print("Current working directory is:", os.getcwd())

# Changing directory
os.chdir('../')
print("Changing directory one level up:", os.getcwd())

Output:
Current working directory is: /home/ayman
Changing directory one level up: /home

If you want to find the directory where the script is located, use os.path.realpath(__file__). It will return a string containing the absolute path to the running script.

Creating a Directory

There are different methods available in the OS module for creating a directory. These are –

  • os.mkdir()

  • os.makedirs()

Using os.mkdir()

os.mkdir() method in Python is used to create a directory named path with the specified numeric mode. This method raises FileExistsError if the directory to be created already exists.

import os

# Directory
directory = "Test_dir"

# Parent Directory path
parent_dir = "/tmp"

# Path
path = os.path.join(parent_dir, directory)

# Create the directory
os.mkdir(path)
print("Directory %s created" % directory)


Output:
Directory 'Test_dir' created

we can pass mode parameter to mkdir function

# os.mkdir(path, mode)

Using os.makedirs()

os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all.

import os
	
# Leaf directory
directory = "leaf_dir"
	
# Parent Directories
parent_dir = "/home/maaelhamid/new_dir/another_dir"
	
# Path
path = os.path.join(parent_dir, directory)
	
# Create the directory
os.makedirs(path)
print("Directory '% s' created" % directory)


Output:
Directory leaf_dir created

# all these dirs are created
# /home/maaelhamid/new_dir/another_dir/leaf_dir

Listing out Files and Directories with Python

os.listdir() method in Python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then the list of files and directories in the current working directory will be returned.

import os
 
# Get the list of all files and directories
# in the root directory
path = "/"
dir_list = os.listdir(path)
 
print("Files and directories in '", path, "' :")
print(dir_list)


Output:
Files and directories in ' / ' :
['snap', 'cdrom', 'lost+found', 'bin', 'home', 'var', 'opt', 'libx32', 'etc', 'lib64', 'swapfile', 'boot', 'run', 'proc', 'media', 'sbin', 'lib', 'tmp', 'mnt', 'root', 'sys', 'dev', 'usr', 'lib32', 'srv', 'src']

Deleting Directory or Files using Python

OS module proves different methods for removing directories and files in Python. These are –

Using os.remove()

os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method.

# Python program to explain os.remove() method
	
# importing os module
import os
	
# File name
file = 'file.txt'
	
# File location
location = "/tmp"
	
# Path
path = os.path.join(location, file)
	
# Remove the file
# 'file.txt'
os.remove(path)

Using os.rmdir()

os.rmdir() method in Python is used to remove or delete an empty directory. OSError will be raised if the specified path is not an empty directory.

import os
	
# Directory name
directory = "dir"
	
# Parent Directory
parent = "/home/ayman"
	
# Path
path = os.path.join(parent, directory)
	
# Remove the Directory
# "dir"
os.rmdir(path)

Commonly Used Functions

  • os.getpid method in Python is used to get the process ID of the current process.

import os

pid = os.getpid()
print(pid)

 
Output:
3663
  • os.name This function gives the name of the operating system dependent module imported. The following names have currently been registered: ‘posix’, ‘nt’, ‘os2’, ‘ce’, ‘java’ and ‘riscos’.

import os

print(os.name)


Output:
posix
  • os.error All functions in this module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. os.error is an alias for built-in OSError exception.

import os

try:
	filename = 'file.txt'
	f = open(filename, 'rU')
	text = f.read()
	f.close()

# Control jumps directly to here if
# any of the above lines throws IOError.
except IOError:
	print('Problem reading: ' + filename)
	

Output:
Problem reading: file.txt
  • os.popen This method opens a pipe to or from command. The return value can be read or written depending on whether the mode is ‘r’ or ‘w’.

import os

fd = "file.txt"

file = open(fd, 'r')
text = file.read()
print(text)
 
# popen() provides a pipe/gateway and accesses the file directly
file = os.popen(fd, 'w')
file.write("Hello")
  • os.close Close file descriptor fd. A file opened using open(), can be closed by close()only. But file opened through os.popen(), can be closed with close() or os.close(). If we try closing a file opened with open(), using os.close(), Python would throw TypeError.

import os

fd = "file.txt"
file = open(fd, 'r')
text = file.read()
print(text)
os.close(file)
  • os.rename A file old.txt can be renamed to new.txt, using the function os.rename(). The name of the file changes only if, the file exists and the user has sufficient privilege permission to change the file.

import os

fd = "file.txt"
os.rename(fd,'New_file.txt')
  • os.path.exists This method will check whether a file exists or not by passing the name of the file as a parameter. OS module has a sub-module named PATH by using which we can perform many more functions.

import os

result = os.path.exists("file_name")
print(result)


Output:
False
  • os.path.getsize In this method, python will give us the size of the file in bytes. To use this method we need to pass the name of the file as a parameter.

import os

size = os.path.getsize("filename")
print("Size of the file is", size," bytes.")


Output:
Size of the file is 221 bytes.

Check official documentation for more OS methods

Last updated