• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / System & OS / Python System Administration

Python System Administration

Author: PFB Staff Writer
Last Updated: August 25, 2020

Overview

The OS module in Python provides a way of using operating system dependent
functionality.

The functions that the OS module provides allows you to interface with the
underlying operating system that Python is running on. (Windows, Mac or
Linux.

You can find important information about your location or about the process.

Before we start, make sure that you have imported the OS module “import os”

OS Functions explained

os.system()	# Executing a shell command

os.stat()	# Get the status of a file

os.environ()    # Get the users environment

os.chdir()   	# Move focus to a different directory

os.getcwd()    	# Returns the current working directory

os.getgid()    	# Return the real group id of the current process

os.getuid()    	# Return the current process’s user id

os.getpid()     # Returns the real process ID of the current process

os.getlogin()   # Return the name of the user logged

os.access()   	# Check read permissions

os.chmod()    	# Change the mode of path to the numeric mode

os.chown()   	# Change the owner and group id

os.umask(mask)  # Set the current numeric umask

os.getsize()   	# Get the size of a file

os.environ()    # Get the users environment

os.uname()   	# Return information about the current operating system

os.chroot(path) # Change the root directory of the current process to path

os.listdir(path)# List of the entries in the directory given by path

os.getloadavg() # Show queue averaged over the last 1, 5, and 15 minutes

os.path.exists()# Check if a path exists

os.walk()   	# Print out all directories, sub-directories and files

os.mkdir(path)	# Create a directory named path with numeric mode mode

os.remove(path)	# Remove (delete) the file path

os.rmdir(path)  # Remove (delete) the directory path

os.makedirs(path)# Recursive directory creation function

os.removedirs(path) # Remove directories recursively

os.rename(src, dst) # Rename the file or directory src to dst

OS Functions Examples

Let’s get started to see how we can use these OS functions.

#Get current working directory with os.getcwd()
print os.getcwd()

#Get the status of a file with os.stat()
print "Getting the status of: ", os.stat('/usr/bin/python')

#Execute a shell command with os.system()
os.system('ls -l')

#Return the current process id with os.getpid()
print os.getpid()
os.chmod(path, mode)

#Change the owner and group id of path to the numeric uid and gid with os.chown()
os.chown(path, uid, gid)

#Processes in the system run queue averaged over the last 1, 5, and 15 minutes
print os.getloadavg()

#Check if a path exists with os.path.exists()
if os.path.exists("file.txt"):

#Create a new directory named 'new_directory' if it doesn't exist already"
os.path.exists("new_directory") or os.mkdir("new_directory")

#Check if the path is a directory or a file with os.path.isdir() & os.path.isfile()
path = "/tmp"
if os.path.isdir(path): print "That's a directory"
if os.path.isfile(path): print "That's a file"

#Create a directory with os.makedir()
print os.mkdir('new_directory', 0666)

#Recursive create directories with os.makedirs()
os.makedirs('dir_a/dir_b/dir_c')

#Remove a directory with os.rmdir()
print os.rmdir('directory')

#Recursively remove empty directories with os.rmdirs()
os.removedirs('dir_a/dir_b/dir_c')

#Rename a file with os.rename()
print os.rename('/path/to/old/file', '/path/to/new/file')

#Rename a file with shutil.move()
print shutil.move('/path/to/old/file', '/path/to/new/file')

#Rename a file with shutil.copy()
print shutil.copy('/path/to/old/file', '/path/to/new/file')

#Get the users home directory
print os.path.expanduser('~')

#Check read permissions with os.access()
path = '/tmp/file.txt'
print os.access(path, os.R_OK)

#Get the users environment with os.environmen()
home =  os.environ['HOME']
print home

#Move focus to a different directory with os.chdir()
print os.chdir('/tmp')

#Print out all directories, sub-directories and files with os.walk()
for root, dirs, files in os.walk("/tmp"):
    print root
    print dirs
    print files

#Get the last time a directory was accessed with os.path.getatime()
os.path.getatime('/tmp')

#Get the last time a directory was modified with os.path.getmtime()
os.path.getmtime('/tmp')

#Get the user ID with os.getuid()
if os.getuid() != 0: print "you are not root"

#Get the group ID with os.getgid()
print os.getgid()

#Return the name of the user logged in with os.getlogin()
print os.getlogin()

#Returns a list of all files in a directory with os.listdir()
for filename in os.listdir("/tmp"):
    print "This is inside /tmp", filename

#Get the size of a file with os.path.getsize()
path.getsize("/tmp/file.txt")

Using Python in your daily work is a good way to automate system administration tasks, when you feel that your shell scripts are to limited.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: OS, System & OS Author: PFB Staff Writer

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us