Python os Module

Python OS Module provides an interface between Python Code and Operating System, through this interface by using different functions you can make some system calls to push OS to do stuff like Opening a File.
Let’s discuss everything about Python OS Module in this article.

How to import os Module?

As usual Python’s OS Module can be used in code by importing it through import os statement. Either you can use from os import * or import os depending upon whether you need some specific function which is inside OS Module or you need whole of OS Module.
(* means some function name here)

import os
from os import getcwd

Common Functions in os Module – Table

FunctionDescription
os.ctermid()Return filenme corresponding to controlling terminal of process
os.getcwd()Return current working directory
os.fspath(path)Return file system representation of path
os.getpid()Return current process id
os.fdopen(fd*args**kwargs)Returns an open file object connected to file descriptor fd
os.close(fd)Close file descriptor fd
os.closerange(fd_low, fd_high)Close all file descriptors from fd_low to fd_high both inclusive
os.fchmod(fd, mode)Changes mode of file given by fd to numeric mode
os.oper(path, flogs, mode=0o777, *, dir_fd=None)Opens file path and set various flags and mode
os.pipe()Create a pipe and return a pair of file desciptors (r, w) which can be used for reading, writing
os.read(fd, n)Read at most n bytes from file descriptor fd
os.sendfile(out_fd, in_fd, offset, count, headers=(), trailers=(), flags=0)Copy count bytes from file descriptor in_fd to file descriptor out_fd starting at offset. Return the number of bytes sent. When EOF is reached return
os.write(fd, str)Write bytestring in str to file descriptor fd
Returns number of byte written
os.writev(fd, buffers)Write contents of buffer to file descriptor fd, here buffer must be a sequence of bytes like objects
os.chdir(path)Change current working directory to path
os.chflags(path, flags, *,
follow_symlinks=True
)
Set flags of path to numeric flag
os.chmod(path, mode, *, dir_fd=None,
follow_symlinks=True
)
Change mode of path to numeric mode
os.chown(path, uid, gid, *,
dir_fd=None, follow_symlinks=True
)
Change owner and group id of path to numeric uid and gid
os.fchdir(fd)Change current working directory to directory represented by file descriptor fd
os.listdir(path = ‘ . ‘ )Return a list containing names of entries in given directory by path
os.mkdir(path, mode=0o777, *, dir_fd=None)Create a directory named path with numeric mode
os.makedirs(name, mode=0o777, exist_ok=False)Recursive directory creation function
os.remove(path, *, dir_fd=None)Removes file path
os.rmdir(path, *, dir_fd=None)Removes directory path

Working with Files using os Module in Python

Below is a Python Code example, showing how Python’s os Module can be used for dealing with files.

import os
import string

def replace(file, search_for, replace_with):
    # replace strings in a text file

    back = os.path.splitext(file)[0] + ".bak"
    temp = os.path.splitext(file)[0] + ".tmp"

    try:
        # remove old temp file, if any
        os.remove(temp)
    except os.error:
        pass

    fi = open(file)
    fo = open(temp, "w")

    for s in fi.readlines():
        fo.write(string.replace(s, search_for, replace_with))

    fi.close()
    fo.close()

    try:
        # remove old backup file, if any
        os.remove(back)
    except os.error:
        pass

    # rename original to backup...
    os.rename(file, back)

    # ...and temporary to original
    os.rename(temp, file)

#
# try it out!

file = "samples/sample.txt"

replace(file, "hello", "tjena")
replace(file, "tjena", "hello")

Working with Directories using os Module in Python

Below is a Python Code example, showing how Python’s os Module can be used for dealing with Directories.

import os

for file in os.listdir("samples"):
    print file

Working with File Attributes using os Module in Python

Below is a Python Code example, showing how Python’s os Module can be used for dealing with File Attributes.

import os
import time

file = "samples/sample.jpg"

def dump(st):
    mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime = st
    print "- size:", size, "bytes"
    print "- owner:", uid, gid
    print "- created:", time.ctime(ctime)
    print "- last accessed:", time.ctime(atime)
    print "- last modified:", time.ctime(mtime)
    print "- mode:", oct(mode)
    print "- inode/dev:", ino, dev

#
# get stats for a filename

st = os.stat(file)

print "stat", file
dump(st)
print

#
# get stats for an open file

fp = open(file)

st = os.fstat(fp.fileno())

print "fstat", file
dump(st)

stat samples/sample.jpg
- size: 4762 bytes
- owner: 0 0
- created: Tue Sep 07 22:45:58 1999
- last accessed: Sun Sep 19 00:00:00 1999
- last modified: Sun May 19 01:42:16 1996
- mode: 0100666
- inode/dev: 0 2

fstat samples/sample.jpg
- size: 4762 bytes
- owner: 0 0
- created: Tue Sep 07 22:45:58 1999
- last accessed: Sun Sep 19 00:00:00 1999
- last modified: Sun May 19 01:42:16 1996
- mode: 0100666
- inode/dev: 0 0

Working with Processes using os Module in Python

Below is a Python Code example, showing how Python’s os Module can be used for dealing with Processes.

import os

if os.name == "nt":
    command = "dir"
else:
    command = "ls -l"

os.system(command)

-rwxrw-r--   1 effbot effbot        76 Oct  9 14:17 README
-rwxrw-r--   1 effbot effbot      1727 Oct  7 19:00 SimpleAsyncHTTP.py
-rwxrw-r--   1 effbot effbot       314 Oct  7 20:29 aifc-example-1.py
-rwxrw-r--   1 effbot effbot       259 Oct  7 20:38 anydbm-example-1.py
...

Working with Daemon Processes using os Module in Python

Below is a Python Code example, showing how Python’s os Module can be used for dealing with Processes.

import os
import time

pid = os.fork()
if pid:
    os._exit(0) # kill original

print "daemon started"
time.sleep(10)
print "daemon terminated"

Finding which user is “Logged in” in Mac Laptop

import os
username = os.getlogin()

This will print out username like gagan for me.

Final Thoughts

If you look at Python’s os Module documentation, then you would find so many functions there. But if your a beginner in Python Programming then don’t give too much emphasis upon learning about stuff in os Module. Rather take a little fatalistic attitude towards this and just keep on doing stuff in Python, as you write more code and try to solve more problems you will gradually learn about os Module Functions.
Happy Coding 🥳

You Might also like

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts