The python OS module provides functions used for interacting with the operating system and also get related information about it. The OS comes under Python's standard utility modules. This module offers a portable way of using operating system dependent functionality.
The python OS module lets us work with the files and directories.
There are some functions in the OS module which are given below:
This function provides the name of the operating system module that it imports.
Currently, it registers 'posix', 'nt', 'os2', 'ce', 'java' and 'riscos'.
import os print(os.name)
It returns the Current Working Directory(CWD) of the file.
import os print(os.getcwd())
The functions in this module defines the OS level errors. It raises OSError in case of invalid or inaccessible file names and path etc.
import os try: # If file does not exist, # then it throw an IOError filename = 'Python.txt' f = open(filename, 'rU') text = f.read() f.close() # The Control jumps directly to here if #any lines throws IOError. except IOError: # print(os.error) will <class 'OSError'> print('Problem reading: ' + filename)
This function opens a file to, or from the command specified and it returns a file object which is connected to a pipe.
import os fd = "python.txt" # popen() is similar to open() file = open(fd, 'w') file.write("This is awesome") file.close() file = open(fd, 'r') text = file.read() print(text) # popen() provides gateway and accesses the file directly file = os.popen(fd, 'w') file.write("This is awesome") # File not closed, shown in next function.
This function closes the associated file with descriptor fd.
import os fr = "Python1.txt" file = open(fr, 'r') text = file.read() print(text) os.close(file)
In this function, a file or directory can be renamed by using the function os.rename(). A user can rename the file if it has privilege to change the file.
import os fd = "python.txt" os.rename(fd,'Python1.txt') os.rename(fd,'Python1.txt')
This function uses real uid/gid to test if the invoking user has access to the path.
import os import sys path1 = os.access("Python.txt", os.F_OK) print("Exist path:", path1) # Checking access with os.R_OK path2 = os.access("Python.txt", os.R_OK) print("It access to read the file:", path2) # Checking access with os.W_OK path3 = os.access("Python.txt", os.W_OK) print("It access to write the file:", path3) # Checking access with os.X_OK path4 = os.access("Python.txt", os.X_OK) print("Check if path can be executed:", path4)