Python Scripting (7 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (345 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

OS Module in Python: All You Need to Know

Published on Sep 25,2019 9.3K Views


Python is one of the most powerful programming languages available in the industry today. Thanks to its wide number of features and great versatility, a lot of complex programming objectives can be achieved in Python quite easily. In this article, we will discuss OS Module in Python in the following order:

 

What is the OS Module in Python?

The OS module in Python is a part of the standard library of the programming language. When imported, it lets the user interact with the native OS Python is currently running on. In simple terms, it provides an easy way for the user to interact with several os functions that come in handy in day to day programming.

OS Module in Python

The OS module and os.path modules are the same and can be easily imported from the standard library, at a moment’s notice.

 

Functions of the OS module

Now that you know the definition of the OS module, let us look at some of its functions.

  • os.name: If you want to know the name and credentials of the current operating system Python is running on then make use of the os.name function. Take a look at the example below to understand its implementation better.
import os 
print(os.name) 

Output:

posix

Note: The above program will give a different output depending upon the operating system you are currently using.

 

  • os.getcwd(): If you want to know the Current Working Directory or CWD that has been used to run your code, then you can make use of this function. Similar to the os.name function, the output of this will vary depending upon the system it is installed on.

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:

C:UsersGFGDesktopModuleOS

Note: If you are using a GFG interpreter, then the directory used by default will be /root.

 

  • os.error: Whenever you are using a module or function in Python that has been imported from the standard library, it will raise an OSError in case you have used incorrect path as well as file names, or have used an argument that has the correct type but is not accepted by the operating system you are currently using.  This function is an alias of the inbuilt OSError exception in Python. Take a look at the example below to understand this better.

import os 
try: 
	# If the file does not exist, 
	# then it would throw an IOError 
	filename = 'GFG.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: GFG.txt

 

  • os.popen(): This function is a part of file object manipulation and is used to open a pipe to and from a command. The return value of this function can be read or written dependent upon your use of r or w. The syntax for this function is as follows,  os.popen(command[, mode[, bufsize]]). The parameters taken into consideration are, mode as well as bufsize. Take a look at the example below to understand this better.

import os 
fd = "GFG.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 the next function.

Output:

Hello

 

  • os.close(): If you want to close the file directory fd, then you can make use of this function. When used, a file needs to be opened first using the open() function and then closed using the close() function. Take a look at the example below to understand this better.

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:UsersGFGDesktopGeeksForGeeksOSFile.py", line 6, in 

    os.close(file)

TypeError: an integer is required (got type _io.TextIOWrapper)

 

  • os.rename(): If in a certain situation you need to rename an old text file that is already present, you can make use of this function. Note: The name of the file in context is only changed if the file already exists in the directory and the user has appropriate permission to do the same. Take a look at the example below to understand this better.

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

Output:

Traceback (most recent call last):

  File "C:UsersGFGDesktopModuleOSGeeksForGeeksOSFile.py", line 3, in 

    os.rename(fd,'New.txt')

FileNotFoundError: [WinError 2] The system cannot find the

file specified: 'GFG.txt' -> 'New.txt'

The os module in Python can be used to access a lot of operating system functions. Now that you know its uses, we hope that you will make use of the same in your day to day programming.

With this, we come to an end of this OS Module in Python. I hope all your doubts about OS Module is cleared now.

To get in-depth knowledge on Python along with its various applications, you can enroll here for live online training with 24/7 support and lifetime access.

Got a question for us? Mention them in the comments section of “Membership Operators in Python” and we will get back to you.

Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

OS Module in Python: All You Need to Know

edureka.co