Commonly Used Functions
Using os.name function
This function gives the name of the operating system dependent module imported. The following names have currently been registered: ‘posix’, ‘nt’, ‘os2’, ‘ce’, ‘java’ and ‘riscos’.
import os
print(os.name)
Output:
posix
Note: It may give different output on different interpreters, such as ‘posix’ when you run the code here.
Using os.error Function
All functions in this module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. os.error is an alias for built-in OSError exception.
This code reads the contents of a file named ‘GFG.txt’. It uses a ‘try…except‘ block to handle potential errors, particularly the ‘IOError‘ that may occur if there’s a problem reading the file.
If an error occurs, it will print a message saying, “Problem reading: GFG.txt.”
import os
try:
filename = 'GFG.txt'
f = open(filename, 'rU')
text = f.read()
f.close()
except IOError:
print('Problem reading: ' + filename)
Output:
Problem reading: GFG.txt
Using os.popen() Function
This method opens a pipe to or from command. The return value can be read or written depending on whether the mode is ‘r’ or ‘w’.
Syntax:
os.popen(command[, mode[, bufsize]])
Parameters mode & bufsize are not necessary parameters, if not provided, default ‘r’ is taken for mode.
This code opens a file named ‘GFG.txt’ in write mode, writes “Hello” to it, and then reads and prints its contents. The use of os.popen
is not recommended, and standard file operations are used for these tasks.
import os
fd = "GFG.txt"
file = open(fd, 'w')
file.write("Hello")
file.close()
file = open(fd, 'r')
text = file.read()
print(text)
file = os.popen(fd, 'w')
file.write("Hello")
Output:
Hello
Note: Output for popen() will not be shown, there would be direct changes into the file.
Using os.close() Function
Close file descriptor fd. A file opened using open(), can be closed by close()only. But file opened through os.popen(), can be closed with close() or os.close(). If we try closing a file opened with open(), using os.close(), Python would throw TypeError.
import os
fd = "GFG.txt"
file = open(fd, 'r')
text = file.read()
print(text)
os.close(file)
Output:
Traceback (most recent call last):
File "C:\Users\GFG\Desktop\w3wikiOSFile.py", line 6, in
os.close(file)
TypeError: an integer is required (got type _io.TextIOWrapper)
Note: The same error may not be thrown, due to the non-existent file or permission privilege.
Using os.rename() Function
A file old.txt can be renamed to new.txt, using the function os.rename(). The name of the file changes only if, the file exists and the user has sufficient privilege permission to change the file.
import os
fd = "GFG.txt"
os.rename(fd,'New.txt')
os.rename(fd,'New.txt')
Output:
Traceback (most recent call last):
File "C:\Users\GFG\Desktop\ModuleOS\w3wikiOSFile.py", line 3, in
os.rename(fd,'New.txt')
FileNotFoundError: [WinError 2] The system cannot find the
file specified: 'GFG.txt' -> 'New.txt'
A file name “GFG.txt” exists, thus when os.rename() is used the first time, the file gets renamed.
Upon calling the function os.rename() second time, file “New.txt” exists and not “GFG.txt” thus Python throws FileNotFoundError.
Using os.remove() Function
Using the Os module we can remove a file in our system using the os.remove() method. To remove a file we need to pass the name of the file as a parameter.
import os #importing os module.
os.remove("file_name.txt") #removing the file.
The OS module provides us a layer of abstraction between us and the operating system.
When we are working with os module always specify the absolute path depending upon the operating system the code can run on any os but we need to change the path exactly. If you try to remove a file that does not exist you will get FileNotFoundError.
Using os.path.exists() Function
This method will check whether a file exists or not by passing the name of the file as a parameter. OS module has a sub-module named PATH by using which we can perform many more functions.
import os
#importing os module
result = os.path.exists("file_name") #giving the name of the file as a parameter.
print(result)
Output:
False
As in the above code, the file does not exist it will give output False. If the file exists it will give us output True.
Using os.path.getsize() Function
In os.path.getsize() function, python will give us the size of the file in bytes. To use this method we need to pass the name of the file as a parameter.
import os #importing os module
size = os.path.getsize("filename")
print("Size of the file is", size," bytes.")
Output:
Size of the file is 192 bytes.
OS Module in Python with Examples
The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality.
The *os* and *os.path* modules include many functions to interact with the file system.