OS Module

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.

It is possible to automatically perform many operating system tasks. The OS module in Python provides functions for creating and removing a directory (folder), fetching its contents, changing and identifying the current directory, etc.


1. os.name: 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 in Windows:

nt

Output in Mac:

posix

2. os.getcwd(): Function os.getcwd(), returns the Current Working Directory(CWD) of the file used to execute the code, can vary from system to system.

import os 
print(os.getcwd()) 
# To print absolute path on your system 
# os.path.abspath('.') 

# To print files and directories in the current directory 
# on your system 


# os.listdir('.') 

Output in Windows:
C:\Users\Greg\AppData\Local\Programs\Python\Python37-32
Output in Mac:
C:\Users\Greg\Desktop\ModuleOS

3. os.error: 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.

import os 
try: 
# If the file does not exist, 
# then it would throw an IOError 
filename = 'Greg.txt'
f = open(filename, 'rU') 
text = f.read() 
f.close() 

# Control jumps directly to here if 
#any of the above lines throws IOError.  
except IOError: 

# print(os.error) will <class 'OSError'> 
print('Problem reading: ' + filename) 
# In any case, the code then continues with 
# the line after the try/except 

Output:
Problem reading: Greg.txt

Working with Directory

4. os.mkdir(): We can create a new directory using the mkdir() function from the OS module.

>>> import os
>>>os.mkdir("d:\\tempdir")

A new directory corresponding to the path in the string argument of the function will be created. If we open D drive in Windows Explorer, we should notice tempdir folder created.

5. os.chdir(): We must first change the current working directory to a newly created one before doing any operations in it. This is done using the chdir() function.


>>> import os

>>> os.chdir("d:\\tempdir")



In order to set the current directory to the parent directory use ".." as the argument in the chdir() function.

>>>os.chdir("d:\\tempdir")
>>>os.getcwd()
'd:\\tempdir'
>>>os.chdir("..")
>>>os.getcwd()
'd:\\'

                                                    File Object Manipulation

6. os.popen(): This method opens a pipe to or from command. The return value can be read or written depending on whether 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.


import os 
fd = "Greg.txt"

# popen() is similar to open() 
file = open(fd, 'w') 
file.write("Hello") 
file.close() 
file = open(fd, 'r') 
text = file.read() 
print(text) 

# popen() provides a pipe/gateway and accesses the file directly 
file = os.popen(fd, 'w') 
file.write("Hello") 
# File not closed, shown in next function. 


Output:
Hello
Note: Output for popen() will not be shown, there would be direct changes into the file.



7. os.close(): 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 = "Greg.txt"

file = open(fd, 'r') 

text = file.read() 

print(text) 

os.close(file) 





Output:

Traceback (most recent call last):
  File "C:\Users\GFG\Desktop\GeeksForGeeksOSFile.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 non-existent of file or permission privilege.



8. os.rename(): 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 user has sufficient privilege permission to change the file.



import os 
fd = "Greg.txt"
os.rename(fd,'New.txt') 
os.rename(fd,'New.txt')


Output:
Traceback (most recent call last):
  File "C:\Users\Greg\Desktop\ModuleOS\Greg.py", line 3, in 
    os.rename(fd,'New.txt')
FileNotFoundError: [WinError 2] The system cannot find the
file specified: 'Greg.txt' -> 'New.txt'
Understanding the Output: A file name “Greg.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 “Greg.txt”
thus Python throws FileNotFoundError.

9. os.listdir(): The listdir() function returns the list of all files and directories in the specified directory.

os.listdir("c:\python37")

Output:
['DLLs', 'Doc', 'fantasy-1.py', 'fantasy.db', 'fantasy.py', 'frame.py',
'gridexample.py', 'include', 'Lib', 'libs', 'LICENSE.txt', 'listbox.py',
'NEWS.txt', 'place.py', 'players.db', 'python.exe', 'python3.dll', 
'python36.dll', 'pythonw.exe', 'sclst.py', 'Scripts', 'tcl', 'test.py',
 'Tools', 'tooltip.py', 'vcruntime140.dll', 'virat.jpg', 'virat.py']
If we don't specify any directory, then list of files and directories in the current working directory will be returned.

os.listdir()

Output:
['.config', '.dotnet', 'python']


Learn more about OS modules in Python docs.




Comments

Popular posts from this blog

Django Template Tags