OS Unit in Python
OS Unit in Python
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.
import os
print(os.getcwd())
# To print absolute path on your system
# os.path.abspath('.')
1|Page
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 = 'GKS.txt'
f = open(filename, 'rU')
text = f.read()
f.close()
import os
fd = "GFG.txt"
2|Page
# 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.
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\gauravOSFile.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.
import os
fd = "GFG.txt"
os.rename(fd,'New.txt')
os.rename(fd,'New.txt')
Output:
3|Page
File "C:\Users\GFG\Desktop\ModuleOS\gauravOSFile.py", line 3, in
os.rename(fd,'New.txt')
FileNotFoundError: [WinError 2] The system cannot find the
file specified: 'GFG.txt' -> 'New.txt'
4|Page