Python OS Module
FREE Online Courses: Click for Success, Learn for Free - Start Now!
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
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
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/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
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
[‘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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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.