Python OS Module

FREE Online Courses: Enroll Now, Thank us Later!

OS Module is one of the Python built-in modules. It comes ready to use in the Python Standard Library. The module contains several useful functions that help us to access, modify, and perform OS-related tasks such as access and modifying directories. In this article, we will learn how to use those functions and what those functions do.

How to use the OS Module in Python?

To use the functions available in the OS module, we need to first import the OS module into our script.

Example of importing the OS module in Python

import os
print(dir(os))

Output

[‘CLD_CONTINUED’, ‘CLD_DUMPED’, ‘CLD_EXITED’, ‘CLD_TRAPPED’, ‘DirEntry’, ‘EX_CANTCREAT’, ‘EX_CONFIG’, ‘EX_DATAERR’, ‘EX_IOERR’, ‘EX_NOHOST’, ‘EX_NOINPUT’, ‘EX_NOPERM’, ‘EX_NOUSER’, ‘EX_OK’, ‘EX_OSERR’, ‘EX_OSFILE’, ‘EX_PROTOCOL’, ‘EX_SOFTWARE’, ‘EX_TEMPFAIL’, ‘EX_UNAVAILABLE’, ‘EX_USAGE’, ‘F_LOCK’, ‘F_OK’, ‘F_TEST’, ‘F_TLOCK’, ‘F_ULOCK’, ‘MutableMapping’, ‘NGROUPS_MAX’, ‘O_ACCMODE’, ‘O_APPEND’, ‘O_ASYNC’, ‘O_CLOEXEC’, ‘O_CREAT’, ‘O_DIRECTORY’, ‘O_DSYNC’, ‘O_EXCL’, ‘O_EXLOCK’, ‘O_NDELAY’, ‘O_NOCTTY’, ‘O_NOFOLLOW’, ‘O_NONBLOCK’, ‘O_RDONLY’, ‘O_RDWR’, ‘O_SHLOCK’, ‘O_SYNC’, ‘O_TRUNC’, ‘O_WRONLY’, ‘POSIX_SPAWN_CLOSE’, ‘POSIX_SPAWN_DUP2’, ‘POSIX_SPAWN_OPEN’, ‘PRIO_PGRP’, ‘PRIO_PROCESS’, ‘PRIO_USER’, ‘P_ALL’, ‘P_NOWAIT’, ‘P_NOWAITO’, ‘P_PGID’, ‘P_PID’, ‘P_WAIT’, ‘PathLike’, ‘RTLD_GLOBAL’, ‘RTLD_LAZY’, ‘RTLD_LOCAL’, ‘RTLD_NODELETE’, ‘RTLD_NOLOAD’, ‘RTLD_NOW’, ‘R_OK’, ‘SCHED_FIFO’, ‘SCHED_OTHER’, ‘SCHED_RR’, ‘SEEK_CUR’, ‘SEEK_DATA’, ‘SEEK_END’, ‘SEEK_HOLE’, ‘SEEK_SET’, ‘ST_NOSUID’, ‘ST_RDONLY’, ‘TMP_MAX’, ‘WCONTINUED’, ‘WCOREDUMP’, ‘WEXITED’, ‘WEXITSTATUS’, ‘WIFCONTINUED’, ‘WIFEXITED’, ‘WIFSIGNALED’, ‘WIFSTOPPED’, ‘WNOHANG’, ‘WNOWAIT’, ‘WSTOPPED’, ‘WSTOPSIG’, ‘WTERMSIG’, ‘WUNTRACED’, ‘W_OK’, ‘X_OK’, ‘_Environ’, ‘__all__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘_check_methods’, ‘_execvpe’, ‘_exists’, ‘_exit’, ‘_fspath’, ‘_fwalk’, ‘_get_exports_list’, ‘_putenv’, ‘_spawnvef’, ‘_unsetenv’, ‘_wrap_close’, ‘abc’, ‘abort’, ‘access’, ‘altsep’, ‘chdir’, ‘chflags’, ‘chmod’, ‘chown’, ‘chroot’, ‘close’, ‘closerange’, ‘confstr’, ‘confstr_names’, ‘cpu_count’, ‘ctermid’, ‘curdir’, ‘defpath’, ‘device_encoding’, ‘devnull’, ‘dup’, ‘dup2’, ‘environ’, ‘environb’, ‘error’, ‘execl’, ‘execle’, ‘execlp’, ‘execlpe’, ‘execv’, ‘execve’, ‘execvp’, ‘execvpe’, ‘extsep’, ‘fchdir’, ‘fchmod’, ‘fchown’, ‘fdopen’, ‘fork’, ‘forkpty’, ‘fpathconf’, ‘fsdecode’, ‘fsencode’, ‘fspath’, ‘fstat’, ‘fstatvfs’, ‘fsync’, ‘ftruncate’, ‘fwalk’, ‘get_blocking’, ‘get_exec_path’, ‘get_inheritable’, ‘get_terminal_size’, ‘getcwd’, ‘getcwdb’, ‘getegid’, ‘getenv’, ‘getenvb’, ‘geteuid’, ‘getgid’, ‘getgrouplist’, ‘getgroups’, ‘getloadavg’, ‘getlogin’, ‘getpgid’, ‘getpgrp’, ‘getpid’, ‘getppid’, ‘getpriority’, ‘getsid’, ‘getuid’, ‘initgroups’, ‘isatty’, ‘kill’, ‘killpg’, ‘lchflags’, ‘lchmod’, ‘lchown’, ‘linesep’, ‘link’, ‘listdir’, ‘lockf’, ‘lseek’, ‘lstat’, ‘major’, ‘makedev’, ‘makedirs’, ‘minor’, ‘mkdir’, ‘mkfifo’, ‘mknod’, ‘name’, ‘nice’, ‘open’, ‘openpty’, ‘pardir’, ‘path’, ‘pathconf’, ‘pathconf_names’, ‘pathsep’, ‘pipe’, ‘popen’, ‘posix_spawn’, ‘posix_spawnp’, ‘pread’, ‘putenv’, ‘pwrite’, ‘read’, ‘readlink’, ‘readv’, ‘register_at_fork’, ‘remove’, ‘removedirs’, ‘rename’, ‘renames’, ‘replace’, ‘rmdir’, ‘scandir’, ‘sched_get_priority_max’, ‘sched_get_priority_min’, ‘sched_yield’, ‘sendfile’, ‘sep’, ‘set_blocking’, ‘set_inheritable’, ‘setegid’, ‘seteuid’, ‘setgid’, ‘setgroups’, ‘setpgid’, ‘setpgrp’, ‘setpriority’, ‘setregid’, ‘setreuid’, ‘setsid’, ‘setuid’, ‘spawnl’, ‘spawnle’, ‘spawnlp’, ‘spawnlpe’, ‘spawnv’, ‘spawnve’, ‘spawnvp’, ‘spawnvpe’, ‘st’, ‘stat’, ‘stat_result’, ‘statvfs’, ‘statvfs_result’, ‘strerror’, ‘supports_bytes_environ’, ‘supports_dir_fd’, ‘supports_effective_ids’, ‘supports_fd’, ‘supports_follow_symlinks’, ‘symlink’, ‘sync’, ‘sys’, ‘sysconf’, ‘sysconf_names’, ‘system’, ‘tcgetpgrp’, ‘tcsetpgrp’, ‘terminal_size’, ‘times’, ‘times_result’, ‘truncate’, ‘ttyname’, ‘umask’, ‘uname’, ‘uname_result’, ‘unlink’, ‘unsetenv’, ‘urandom’, ‘utime’, ‘wait’, ‘wait3’, ‘wait4’, ‘waitpid’, ‘walk’, ‘write’, ‘writev’]

In the above code example, we imported the OS module and used the built-in dir() function to get a list of all functions and variables present in the OS module.

Functions in Python OS Module

From the previous code example, we can see that there are plenty of functions available to use in the OS module. Before diving into those functions, we must first learn about the Current Working Directory in Python.

Current Working Directory in Python

Current Working Directory (CWD) is the directory where our Python file is located. The OS module lets us access and modify CWD using getcwd() and chdir() functions respectively. Let’s understand those functions.

1. getcwd() in Python

The getcwd() function returns the current working directory.

Example of using getcwd() in Python

import os
print(os.getcwd())

Output

/Users/apple/PythonProjects/PythonGeeks

2. chdir(path) in Python

The chdir() function changes the Current Working Directory.

Example of using chdir() in Python

import os

print(os.getcwd())
os.chdir("/Users/apple/PythonProjects/PythonGeeks2")
print(os.getcwd())

Output

/Users/apple/PythonProjects/PythonGeeks

/Users/apple/PythonProjects/PythonGeeks2

3. listdir(path) in Python

The function returns a list of names of all files and folders present in the Current Working Directory.

Example of using listdir() in Python

import os
print(os.listdir())

Output

[OS_demo.py’, main.py’, math_demo.py’, ‘imgs”]

4. mkdir(path[, mode]) in Python

The mkdir() function creates a new directory . It raises a FileNotFoundError when any intermediary directory is not found. If the directory already exists, then it raises a FileExistsError.

Example of using mkdir() in Python

import os
print(os.listdir())
os.mkdir("Fruit") # creates a directory called Fruit
print(os.listdir())

Output

[‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]

[‘Fruit’, ‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]

5. makedirs(path[, mode])

The makedirs() function creates new directories. Unlike mkdir(), it doesn’t raise an error. Instead, it creates all the missing sub-directories. If the directory already exists, then it raises a FileExistsError.

Example of using makedirs() in Python

import os

print("Before Creating:", os.listdir())
os.makedirs("vehicles/four_wheeler/car")
print("After Creating:", os.listdir())
print("Directory created: vehicles/four_wheeler/car")

Output

Before Creating: [‘Fruit’, ‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]

After Creating: [‘vehicles’, ‘Fruit’, ‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]

Directory created: vehicles/four_wheeler/car

6. removedirs(path) in Python

The function removes an existing directory including all sub-directories. It raises a FileNotFoundError if the directory is not found.

Example of using removedirs() in Python

import os

print("Before Removing:", os.listdir())
os.removedirs("vehicles/four_wheeler/car")
print("After Removing:", os.listdir())
print("Directory Removed: vehicles/four_wheeler/car")

Output

Before Removing: [‘vehicles’, ‘Fruit’, ‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]
After Removing: [‘Fruit’, ‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]
Directory Removed: vehicles/four_wheeler/car

7. rmdir(path) in Python

The rmdir() function removes an existing directory. It raises a FileNotFoundError if the directory is not found. Unlike removedirs(), it does not remove sub-directories.

Example of using rmdir() in Python

import os

print("Before Removing:", os.listdir())
os.rmdir("Fruit2")
print("After Removing:", os.listdir())
print("Directory Removed: Fruitr")

Output

Before Removing: [‘Fruit’, ‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]After Removing: [‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]

Directory Removed: Fruit

8. popen(command[, mode[. bufsize]])

The popen() function opens a pipe to or from command. It needs two arguments, file name, and mode. The mode can be either ‘r’ to read or ‘w’ to write. Depending on the mode, we can either write or simply read the file.

Example of using popen() in Python

import os

file_name = "apple.txt"
file = os.popen(file_name, 'w')
file.write("Apples are healthy")
file = os.popen(file_name, 'r')
print(file.read())

Output

Apples are healthy

9. close(fd) in Python

The close() function closes a file that is opened by popen() or pipe().

Example of using close() in Python

import os

file_name = "apple.txt"
file = os.popen(file_name, 'w')
file.write("Apples are healthy")
os.close(file)
print("File is Closed")

Output

File is Closed

10. renames(old, new)

The function renames a file or a directory. It needs two arguments, the current name of the file and the new name of the file.

Example of using renames() in Python

import os

print("Before renaming:", os.listdir())
os.renames("apple.txt", "Mango.txt")
print("After renaming:", os.listdir())

Output

Before renaming: [‘apple.txt’, ‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]
After renaming: [‘Mango.txt’, ‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]

11. remove(path) in Python

The function permanently removes or deletes an existing file. It is an irreversible action and does not work on directories.

Example of using remove() in Python

import os

print("Before removing:", os.listdir())
os.remove('Mango.txt')
print("After removing:", os.listdir())

Output

Before removing: [‘Mango.txt’, ‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]

After removing: [‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]

12. unlink(path) in Python

The function does exactly what remove() does. It permanently removes an existing file and does not work on directories.

Example of using unlink() in Python

import os

print("Before removing:", os.listdir())
os.unlink('math_demo.py')
print("After removing:", os.listdir())

Output

Before removing: [‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]

After removing: [‘OS_demo.py’, ‘main.py’, ‘imgs’]

13. walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

The walk() is a generator. It takes a directory as one positional argument. It walks the passed directory and for every directory it goes, it yields three values, a string of the directory path, a list of directories in that path, and a list of files in that path.

Example of using walk() in Python

import os

for i, j, k in os.walk(os.getcwd()):
   print("path =", i)
   print("List of directories =", j)
   print("List of files =", k)

Output

path = /Users/apple/PythonProjects/PythonGeeks

List of directories = [imgs]

List of files = [‘OS_demo.py’, ‘main.py’]

path = /Users/apple/PythonProjects/PythonGeeks/imgs

List of directories = []
List of files = [‘img1.png’]

14. system(command) in Python

The system() function allows us to run shell commands from the Python environment.

Example of using system() in Python

import os
os.system("Python --version")

Output

Python 3.8.5

15. path.exists(path) in Python

The function exists() is present inside the sub-module path. It takes either a file name or a directory name as its argument and verifies whether it exists or not. It returns True if the passed file exists, otherwise, it returns False.

Example of using path.exists() in Python

import os

print(os.listdir())
print(os.path.exists('modules'))
print(os.path.exists('os.py'))

Output

[‘OS_demo.py’, ‘main.py’, ‘imgs’]

True

False

16. path.get_size(path) in Python

The function get_size() is located inside the sub-module path. It takes either a file name or a directory name as its argument and returns the size of the passed file or directory in bytes.

Example of using path.get_size() in Python

import os
print(os.path.getsize('main.py'))

Output

1852

17. getgid() in Python

The function getgid() returns the current process’s real group id.

Example of using getgid() in Python

import os
print(os.getgid())

Output

20

18. getpid() in Python

The function getpid() returns the current process’s process id.

Example of using getpid() in Python

import os
print(os.getpid())

Output

7062

19. getuid() in Python

The function getuid() returns the user id of the current process. It is also known as UID.

Example of using getuid() in Python

import os
print(os.getuid())

Output

501

20. access(path, mode) in Python

The function access() tests for access to the path. It uses either UID or GID. It has two required parameters, path, and mode. For the parameter path, we can pass any string representing the path as an argument. For the parameter mode, we can only pass any one of the following variables.

F_OK – This mode verifies the existence of the path.
R_OK – This mode tests the readability of the path
W_OK – This mode tests writability of the path
X_OK – This mode is to verify whether the passed file can be executed or not.

Example of using access() in Python

import os
print(os.access('imgs', os.F_OK))

Output

True

21. stat(path) in python

The function executes a stat system call on the passed path and returns the following information about the path.

  • st_mode = protection bits
  • st_ino = inode number
  • st_dev = device id
  • st_nlink = Number of hard links
  • st_uid = user id
  • st_gid = group id
  • st_size = size of file in bytes
  • st_atime = time of the latest access
  • st_mtime = time of the latest modification
  • st_ctime = time of the latest metadata change

Example of using stat() in Python

import os
print(os.stat("modules"))

Output

result(st_mode=16877, st_ino=38962741, st_dev=16777220, st_nlink=8, st_uid=501, st_gid=20, st_size=256, st_atime=1623277776, st_mtime=1622958780, st_ctime=1622958780)

22. chflags(path, flags) in Python

This function sets the flags of the path to the numeric flags. It has no return value. The function is only available on the Unix operating system. We can pass a combination (bitwise or) of the following values to the flag parameter.

  • UF_NODUMP = Do not dump the file
  • UF_IMMUTABLE = May not change the file
  • UF_APPEND = May only the file be appended to
  • UF_NOUNLINK = May not rename or delete the file
  • UF_OPAQUE = The directory is opaque when viewed through a union stack
  • SF_ARCHIVED = May archive the file
  • SF_IMMUTABLE = May not change the file
  • SF_APPEND = May only the file be appended to
  • SF_NOUNLINK = May not rename or delete the file
  • SF_SNAPSHOT = A snapshot file

Example of using chflags() in Python

import os
import stat
print(os.chflags("modules", stat.SF_NOUNLINK))

Output

None

23. chmod(path, mode) in Python

This function changes the mode of the path to the passed numeric mode. It has no return value. We can pass a combination (bitwise or) of the following values to the mode parameter.

  • S_ISUID = Set user ID
  • S_ISGID = Set group ID
  • S_ENFMT = Enforced record locking
  • S_ISVTX = Save text image
  • S_IREAD = Read by owner
  • S_IWRITE = Write by owner
  • S_IEXEC = Execute by owner
  • S_IRWXU = Read, write, and execute by owner
  • S_IRUSR = Read by owner
  • S_IWUSR = Write by owner
  • S_IXUSR = Execute by owner
  • S_IRWXG = Read, write, and execute by group
  • S_IRGRP = Read by group
  • S_IWGRP = Write by group
  • S_IXGRP = Execute by group
  • S_IRWXO = Read, write and execute by others
  • S_IROTH = Read by others
  • S_IWOTH = Write by others
  • S_IXOTH = Execute by others

Example of using chmod() in Python

import os
import stat
print(os.chmod("modules", stat.S_IRWXU))

Output

None

24. chroot(path) in Python

The function changes the root directory of the current process to the passed path. The function executes only if we have super-user privileges. It has no return value.

Example of using chroot() in Python

import os
print(os.chroot("modules"))

Output

None

25. closerange(fd_low, fd_high) in Python

The function closes all file descriptors ranging from fd_low to fd_high. The function ignores errors and has no return value.

Example of using closerange() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_WRONLY | os.O_CREAT)
fd2 = os.open("modules/file2.txt", os.O_WRONLY | os.O_CREAT)

print(os.closerange(fd1, fd2))

Output

None

26. ctermid() in python

The function returns a name of the file that is related to the controlling terminal of the process.

Example of using ctermid() in Python

import os
print(os.ctermid())

Output

/dev/tty

27. dup(fd) in Python

The function creates and returns a duplicate of the file descriptor fd.

Example of using dup() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_WRONLY | os.O_CREAT)
d1_fd1 = os.dup(fd1)
os.close(d1_fd1)
print("file closed using the duplicate descriptor")

Output

file closed using the duplicate descriptor

28. dup2(fd, fd2)

The function creates and returns the duplicate file descriptors from fd to fd2.

Example of using dup2() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_WRONLY | os.O_CREAT)
fd2 = os.open("modules/fil2.txt", os.O_WRONLY | os.O_CREAT)
d1_fd1 = os.dup2(fd1, fd2)
os.close(d1_fd1)
print("file closed using the duplicate descriptor")

Output

file closed using the duplicate descriptor

29. fchdir(fd)

The function changes the CWD to the passed descriptor’s directory.

Example of using fchdir() in Python

import os
print(os.getcwd())
fd1 = os.open("modules", os.O_RDONLY)
os.fchdir(fd1)
print(os.getcwd())

Output

/Users/apple/PycharmProjects/PythonGeeks/Articles/Users/apple/PycharmProjects/PythonGeeks/Articles/modules

30. fchmod(fd, mode)

The function changes the file mode to numeric mode. We need to pass a file descriptor of the file. It has no return value. We can pass a combination (bitwise or) of the following values to the mode parameter.

  • S_ISUID = Set user ID
  • S_ISGID = Set group ID
  • S_ENFMT = Enforced record locking
  • S_ISVTX = Save text image
  • S_IREAD = Read by owner
  • S_IWRITE = Write by owner
  • S_IEXEC = Execute by owner
  • S_IRWXU = Read, write, and execute by owner
  • S_IRUSR = Read by owner
  • S_IWUSR = Write by owner
  • S_IXUSR = Execute by owner
  • S_IRWXG = Read, write, and execute by group
  • S_IRGRP = Read by group
  • S_IWGRP = Write by group
  • S_IXGRP = Execute by group
  • S_IRWXO = Read, write and execute by others
  • S_IROTH = Read by others
  • S_IWOTH = Write by others
  • S_IXOTH = Execute by others

Example of using fchmod() in Python

import os
import stat
fd1 = os.open("modules/file1.txt", os.O_RDONLY)
print(os.chmod(fd1, stat.S_IRWXU))

Output

None

31. fchown(fd, uid, gid)

The function changes the UID and GID of the file to the numeric UID and GID respectively. We need to pass a file descriptor of the file. It has no return value. Passing -1 as UID or GID makes no change.

Example of using fchown() in Python

import os
fd1 = os.open("modules", os.O_RDONLY)
print(os.fchown(fd1, -1, 100))

Output

None

32. fdatasync(fd)

The function force writes the file to the disk. We need to pass a file descriptor of the file. It has no return value. It also doesn’t force write metadata, so it is comparatively faster than fsync().

Example of using fdatasync() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_RDWR)
os.write(fd1, "PythonGeeks")
print(os.fdatasync(fd1))

Output

None

32. fdopen(fd[, mode[, bufsize]])

This function is used to open a file. It returns an open file object. We need to pass a file descriptor of the file.

Example of using fdopen() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_RDWR)
fd2 = os.fdopen(fd1, "w+")
fd2.write("PythonGeeks")
file = os.read(fd1, 200)
print(file)

Output

b’PythonGeeks’

33. fpathconf(fd, name)

The function returns system configuration information related to an open file. We can get the possible name arguments by using the fpathconf variable.

Example of using fpathconf() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_RDWR)
print(os.pathconf_names)
print(os.fpathconf(fd1, 'PC_ALLOC_SIZE_MIN'))

Output

{‘PC_ALLOC_SIZE_MIN’: 16, ‘PC_ASYNC_IO’: 17, ‘PC_CHOWN_RESTRICTED’: 7, ‘PC_FILESIZEBITS’: 18, ‘PC_LINK_MAX’: 1, ‘PC_MAX_CANON’: 2, ‘PC_MAX_INPUT’: 3, ‘PC_MIN_HOLE_SIZE’: 27, ‘PC_NAME_MAX’: 4, ‘PC_NO_TRUNC’: 8, ‘PC_PATH_MAX’: 5, ‘PC_PIPE_BUF’: 6, ‘PC_PRIO_IO’: 19, ‘PC_REC_INCR_XFER_SIZE’: 20, ‘PC_REC_MAX_XFER_SIZE’: 21, ‘PC_REC_MIN_XFER_SIZE’: 22, ‘PC_REC_XFER_ALIGN’: 23, ‘PC_SYMLINK_MAX’: 24, ‘PC_SYNC_IO’: 25, ‘PC_VDISABLE’: 9}1

34. fstat(fd)

The function executes a stat system call on the passed path. It is similar to stat() but instead of passing a string, we need to pass a file descriptor. It returns the following information about the path.

  • st_mode = protection bits
  • st_ino = inode number
  • st_dev = device id
  • st_nlink = Number of hard links
  • st_uid = user id
  • st_gid = group id
  • st_size = size of file in bytes
  • st_atime = time of the latest access
  • st_mtime = time of the latest modification
  • st_ctime = time of the latest metadata change

Example of using stat() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_RDWR)
print(os.fstat(fd1))

Output

os.stat_result(st_mode=33261, st_ino=39761914, st_dev=16777223, st_nlink=1, st_uid=501, st_gid=20, st_size=24, st_atime=1623585531, st_mtime=1623585531, st_ctime=1623585531)

35. fstatvfs(fd)

The function executes a statvfs system call on the passed path. We need to pass a file descriptor of the file. It returns the following information about the path

  • f_bsize = block size of the file system
  • f_frsize = size of fragment
  • f_blocks = fs size in f_frsize units
  • f_bfree = free blocks
  • f_bavail = free blocks for non-root
  • f_files = inodes
  • f_ffree = free inodes
  • f_favail = free inodes for non-root
  • f_fsid = id of file system
  • f_flag = mount flags
  • f_namemax = length of maximum filename

Example of using fstatvfs() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_RDWR)
print(os.fstatvfs(fd1))

Output

os.statvfs_result(f_bsize=1048576, f_frsize=4096, f_blocks=61202533, f_bfree=9709560, f_bavail=5131334, f_files=2448101320, f_ffree=2446235613, f_favail=2446235613, f_flag=0, f_namemax=255)

36. fsync(fd)

The function force writes the file to the disk including metadata. We need to pass a file descriptor of the file. Since it also writes metadata, it is comparatively slower than fdatasync(). It has no return value.

Example of using fsync() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_RDWR)
os.write(fd1, "PythonGeeks")
print(os.fsync(fd1))

Output

None

37. ftruncate(fd, length)

This function truncates the file. We need to pass a file descriptor of the file and it has no return value.

Example of using ftruncate() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_RDWR)
os.write(fd1, "PythonGeeks")
print(os.ftruncate(fd1, 20))

Output

None

38. getcwdu()

This function returns the Unicode of the Current Working Directory. It has no parameters.

Example of using getcwdu() in Python

import os
print(os.getcwdu())

Output

/Users/apple/PycharmProjects/PythonGeeks/Articles

39. getenv(key, default=None)

The function returns the value of the passed environmental variable. It returns the default value if the passed key is not found.

Example of using getenv() in Python

import os
print(os.getenv("HOME"))

Output

/Users/apple

40. isatty(fd)

The function returns True if the file descriptor is open and connected to a tty(-like) device. Otherwise, it returns False.

Example of using isatty() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_RDWR)
os.write(fd1, os.getcwdb())
print(os.isatty(fd1))

Output

False

41. lchflags(path, flags)

This function sets the flags of the path to the numeric flags. It has no return value. The function is only available on the Unix operating system. We can pass a combination (bitwise or) of the following values to the flag parameter.

  • UF_NODUMP = Do not dump the file
  • UF_IMMUTABLE = May not change the file
  • UF_APPEND = May only the file be appended to
  • UF_NOUNLINK = May not rename or delete the file
  • UF_OPAQUE = The directory is opaque when viewed through a union stack
  • SF_ARCHIVED = May archive the file
  • SF_IMMUTABLE = May not change the file
  • SF_APPEND = May only the file be appended to
  • SF_NOUNLINK = May not rename or delete the file
  • SF_SNAPSHOT = A snapshot file

Example of using lchflags() in Python

import os
import stat
print(os.lchflags("modules", stat.UF_APPEND))

Output

None

42. lchmod(path, mode)

This function changes the mode of the path to the passed numeric mode. It changes the mode of the symlink if the path is a symlink. It has no return value. We can pass a combination (bitwise or) of the following values to the mode parameter.

  • S_ISUID = Set user ID
  • S_ISGID = Set group ID
  • S_ENFMT = Enforced record locking
  • S_ISVTX = Save text image
  • S_IREAD = Read by owner
  • S_IWRITE = Write by owner
  • S_IEXEC = Execute by owner
  • S_IRWXU = Read, write, and execute by owner
  • S_IRUSR = Read by owner
  • S_IWUSR = Write by owner
  • S_IXUSR = Execute by owner
  • S_IRWXG = Read, write, and execute by group
  • S_IRGRP = Read by group
  • S_IWGRP = Write by group
  • S_IXGRP = Execute by group
  • S_IRWXO = Read, write and execute by others
  • S_IROTH = Read by others
  • S_IWOTH = Write by others
  • S_IXOTH = Execute by others

Example of using lchmod() in Python

import os
import stat
print(os.lchmod("modules", stat.S_IRWXU))

Output

None

43. lchown(path, uid, gid)

The function changes the UID and GID of the file to the numeric UID and GID respectively. It has no return value. Passing -1 as UID or GID makes no change.

Example of using lchown() in Python

import os
print(os.lchown("modules", -1, 100))

Output

None

44. link(src, dst)

This function creates a hard link pointing to an src called dst. It is used to copy an existing file. It has no return value.

Example of using link() in Python

import os
print(os.link("modules/file1.txt", "modules/file5.txt"))

Output

None

45. lseek(fd, pos, how)

This function changes the passed file descriptor’s current position to the passed position. The third parameter can be used to modify it. It has no return value.

Example of lseek() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_RDWR)
os.write(fd1, "PythonGeeks".encode())
os.lseek(fd1, 1, 0)
print(os.read(fd1, 100))

Output

b’PythonGeeks’

46. lstat(path)

The function executes a stat system call on the passed path. It is similar to stat() but it doesn’t follow the symbolic link. It returns the following information about the path

  • st_mode = protection bits
  • st_ino = inode number
  • st_dev = device id
  • st_nlink = Number of hard links
  • st_uid = user id
  • st_gid = group id
  • st_size = size of file in bytes
  • st_atime = time of the latest access
  • st_mtime = time of the latest modification
  • st_ctime = time of the latest metadata change

Example of using lstat() in Python

import os
print(os.lstat("modules/file1.txt"))

Output

os.stat_result(st_mode=33261, st_ino=39761914, st_dev=16777223, st_nlink=2, st_uid=501, st_gid=20, st_size=12, st_atime=1623589700, st_mtime=1623589681, st_ctime=1623589681)

47. major(device)

The function returns the major number of the device. We need to pass the raw device number as its argument. The raw device number can be found by using the stat() function.

Example of using major() in Python

import os
device = os.lstat("modules/file1.txt").st_dev
print(os.major(device))

Output

1

48. minor(device)

The function returns the minor number of the device. We need to pass the raw device number as its argument. The raw device number can be found by using the stat() function.

Example of using minor() in Python

import os
device = os.lstat("modules/file1.txt").st_dev
print(os.minor(device))

Output

7

49. makedev(major, minor)

This function returns the raw device number. We need to pass the major and minor numbers of the device. The major and minor numbers can be found by using the major() and minor() functions respectively.

Example of using makedev() in Python

import os
device = os.lstat("modules/file1.txt").st_dev
print(device)
minor = os.minor(device)
major = os.major(device)
print(os.makedev(major, minor))

Output

16777223
16777223

50. mkfifo(path[, mode=0o66])

The function creates a named pipe (FIFO) with the name path. It has no return value.

Example of using mkfifo() in Python

import os
print(os.mkfifo("modules/file6.txt"))

Output

None

51. mknod(filename[, mode=0o600, device=0])

The function creates a filesystem. The passed filename will be the name of the file system. It has no return value.

Example of using mknod() in Python

import os
print(os.mknod("modules/modules2"))

Output

None

52. open(file, flags[, mode=0o777])

The function opens the passed file and returns the opened file descriptor. The default value of the parameter mode is 0o777. We can pass a combination (bitwise or) of the following values to the flag parameter.

  • O_RDONLY = open only to read
  • O_WRONLY = open only to write
  • O_RDWR = open to both read and write
  • O_NONBLOCK = does not block on open
  • O_APPEND = append on each write
  • O_CREAT = create the file
  • O_TRUNC = set truncate size to 0
  • O_EXCL = error if created and file exists
  • O_SHLOCK = atomically obtains a shared lock
  • O_EXLOCK = atomically obtains an exclusive lock
  • O_DIRECT = eliminate cache effects
  • O_FSYNC = to synchronous writes
  • O_NOFOLLOW = does not follow symlinks

Example of using open() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_RDONLY)
print(os.read(fd1, 100))

Output

b’PythonGeeks’

53. openpty()

The function opens a pseudo-terminal pair and returns a master and slave descriptor for pty and tty respectively.

Example of using openpty() in Python

import os
print(os.openpty())

Output

(3, 4)

54. pathconf(path, name)

The function returns the system configuration information of the passed file.

Example of using pathconf() in Python

import os
print(os.pathconf("modules", "PC_NAME_MAX"))

Output

255

55. pipe()

The function creates a pipe and returns an ‘r’ and ‘w’ descriptor for reading and writing respectively.

Example of using pipe() in Python

import os
print(os.pipe())

Output

(3, 4)

56. read(fd, n)

The function returns a string containing the maximum passed bytes from the file represented by the passed file descriptor.

Example of using the read() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_RDONLY)
print(os.read(fd1, 100))

Output

b’PythonGeeks’

57. readlink(path)

The function returns a string containing the path to which the symbolic link points.

Example of using readlink() in Python

import os
path1 = "modules"
path2 = "modules2/modules4"
os.symlink(path1, path2)
print(os.readlink(path2))

Output

modules

58. rename(src, dst)

The function is used to rename a file or directory. It has no return value. It raises an OSError if the file already exists.

Example of using rename() in Python

import os
print(os.rename("modules2", "modules3"))

Output

None

59. rmdir(path)

The function removes the passed directory. It raises an OSError if the directory is not empty. It has no return value.

Example of using rmdir() in Python

import os
print(os.rmdir("modules2"))

Output

None

60. statvfs(path)

The function executes a statvfs system call on the passed path. It returns the following information about the path

  • f_bsize = block size of the file system
  • f_frsize = size of fragment
  • f_blocks = fs size in f_frsize units
  • f_bfree = free blocks
  • f_bavail = free blocks for non-root
  • f_files = inodes
  • f_ffree = free inodes
  • f_favail = free inodes for non-root
  • f_fsid = id of file system
  • f_flag = mount flags
  • f_namemax = length of maximum filename

Example of using fstatvfs() in Python

import os
print(os.statvfs("modules/file1.txt"))

Output

os.statvfs_result(f_bsize=1048576, f_frsize=4096, f_blocks=61202533, f_bfree=9543660, f_bavail=4703256, f_files=2448101320, f_ffree=2446234385, f_favail=2446234385, f_flag=0, f_namemax=255)

61. symlink(src, dst)

The function creates a symbolic link that points to the passed src. It has no return value.

Example of using symlink() in Python

import os
path1 = "modules"
path2 = "modules2/modules5"
print(os.symlink(path1, path2))

Output

None

62. tcgetpgrp(fd)

The function returns the process group associated with the terminal of the passed file descriptor.

Example of using the tcgetpgrp() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_RDONLY)
print(os.tcgetpgrp(fd1))

Output

1273

63. tcsetpgrp(fd, pg)

The function sets the process group associated with the terminal of the passed file descriptor. It has no return value.

Example of using the tcsetpgrp() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_RDONLY)
print(os.tcsetpgrp(fd1, 1978))

Output

None

64. ttyname(fd)

The function returns a string containing the terminal device linked to the passed file descriptor.

Example of using ttyname() in Python

import os
master, slave = os.openpty()
print(os.ttyname(slave))

Output

/dev/ttys000

65. uname()

The function returns an imported operating system-dependent module’s name.

Example of using uname() in Python

import os
print(os.uname())

Output

posix.uname_result(sysname=’Darwn’, nodename=’MacBook-Pro.local’, release=’20.5.0′, version=’Darwn Kernel Version 20.5.0: Sat May 8 05:10:33 PDT 2021; root:xnu-7195.121.3~9/RELEASE_X86_64′, machine=’x86_64′)

66. utime(path, times)

The function puts the access and modified times of the passed path. It has no return value.

Example of using utime() in Python

import os
print(os.utime("modules", (1000000, 3000000)))

Output

None

67. write(fd, str)

The function writes the passed byte-string in the passed file descriptor and returns the number of bytes written.

Example of using write() in Python

import os
fd1 = os.open("modules/file1.txt", os.O_RDWR)
print(os.write(fd1, "PythonGeeks".encode()))

Output

11

Variables in the OS Module

Not only functions but the OS module also has a number of useful variables. Let’s understand some of those variables.

68. name

This variable returns the OS imported dependent module. Six modules are registered till now. They are, ‘posix’, ‘os2’, ‘ce’, ‘nt’, ‘riscos, and ‘java’

Example of using the variable name in Python

import os
print(os.name)

Output

posix

69. environ

The variable returns a dictionary of all environmental variables and their values of the system.

Example of using the variable environ in Python

print(f"There are {len(os.environ)} environmental variables")
print("Home =", os.environ['HOME'])

Output

There are 30 environmental variablesHome = /Users/apple

70. environb

The variable returns a dictionary of bytestrings of all environmental variables and their values of the system.

Example of using the variable environb in Python

import os
print(f"There are {len(os.environb)} environmental variables")
print("Home =", os.environb[b'HOME'])

Output

There are 30 environmental variablesHome = b’/Users/apple’

71. error

We can use os.error to catch all errors related to the system. It is an environment error class for both OS errors and I/O errors.

Example of using the variable error in Python

import os
print(os.listdir())
try:
   print(os.remove("mango"))
except os.error:
   print("Error! the file you are trying to delete does"
    " not exist")

Output

[‘OS_demo.py’, ‘main.py’, ‘imgs’]Error! The file you are trying to delete does not exist

Benefits of using the OS Module in Python

  • The module doesn’t depend on the host OS. So it works the same on all operating systems.
  • We can create platform-independent programs using the OS module.
  • It helps us to interact with the operating system.

Python Interview Questions on the OS Module

Q1. Write a Python program to change the CWD to ‘/Users/apple/PythonProjects/NewCWD’ and print the CWD.

Ans 1. Complete code is as follows:

import os
os.chdir('/Users/apple/PythonProjects/NewCWD')
print(os.getcwd())

Output

/Users/apple/PythonProjects/NewCWD

Q2. Write a Python program to create directory ‘/Users/apple/Practice/Questions/Answers’ including the sub-directories.

Ans 2. Complete code is as follows:

import os
os.makedirs('/Users/apple/Practice/Questions/Answers')
print("Directory created")

Output

Directory created

Q3. Write a Python program to get the user id of the current process.

Ans 3. Code is as follows:

import os
print(os.getuid())

Output

501

Q4. Write a Python program to check whether the path ‘/Users/apple/Aeroplane/’ exists or not.

Ans 4. Code is as follows:

import os
print(os.path.exists('/Users/apple/Aeroplane/'))

Output

False

Q5. Sam wrote the below code to rename a file that doesn’t exist. What is the output of the code?

import os

try:
   os.renames('Formulas.txt', 'Math Formulas.txt')
except NameError:
   print("File not found")
except os.error:
   print("File not renamed")
else:
   print("File renamed")

Ans 5. The output of the given code is

Output

File not renamed

Python OS Module Quiz

Conclusion

In this article, we learned about the OS modules, several useful variables, and functions available in the module, and ways to use them. Furthermore, if you have any queries or thoughts, please feel free to share them with us in the comment section.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google | Facebook


Leave a Reply

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