52. The os and sys module
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. This os and os.path modules include many functions to interact with the file system.
Following are some functions in OS module:
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
>>>os.name
'nt'
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.
>>> os.getcwd()
'C:\\Users\\binuvp\\AppData\\Local\\Programs\\Python\\Python38-32'
3.os.listdir('.').
To print files and directories in the current directory on your system
>>> os.listdir('.')
['are.py', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mymodule.py', 'NEWS.txt', 'polygon.py', 'python.exe', 'python3.dll', 'python38.dll', 'pythonw.exe', 's.py', 'Scripts', 'student.py', 't.py', 'tcl', 'test.py', 'Tools', 'vcruntime140.dll', '__pycache__']
4.os.chdir('..')
This function is used to change the CWD
>>> os.getcwd()
'C:\\Users\\binuvp\\AppData\\Local\\Programs\\Python\\Python38-32'
>>> os.chdir('..')
>>> os.getcwd()
'C:\\Users\\binuvp\\AppData\\Local\\Programs\\Python'
>>> os.chdir('Python38-32')
>>> os.getcwd()
'C:\\Users\\binuvp\\AppData\\Local\\Programs\\Python\\Python38-32'
5.os.mkdir(path)
This will create a test directory in C drive
6.os.rmdir(path)
Remove the directory temp
7.os.remove(path)
Remove a file
>>> os.listdir()
['are.py', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mymodule.py', 'NEWS.txt', 'polygon.py', 'python.exe', 'python3.dll', 'python38.dll', 'pythonw.exe', 's.py', 'Scripts', 'student.py', 't.py', 'tcl', 'test.py', 'Tools', 'vcruntime140.dll', '__pycache__']
>>> os.remove('s.py')
>>> os.listdir()
['are.py', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mymodule.py', 'NEWS.txt', 'polygon.py', 'python.exe', 'python3.dll', 'python38.dll', 'pythonw.exe', 'Scripts', 'student.py', 't.py', 'tcl', 'test.py', 'Tools', 'vcruntime140.dll', '__pycache__']
8.os.rename(old.new)
Renames the file or directory named old to new
8.os.walk
The method walk() generates the file names in a directory tree by walking the tree either top-down or bottom-up.
For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
root : Prints out directories only from what you specified.dirs : Prints out sub-directories from root.
files : Prints out all files from root and directories.
The following code will print all files in the root directory c:\\bvp and its sub directories
( University question)
import os
os.chdir('c:\\bvp')
for (root,dirs,files) in os.walk('.', topdown=True):
print(root )
print(dirs )
print(files)
print('--------------------------------')
os.path module functions
1.os.path.isfile(path)
This function is used to test whether the argument specified is a file
>>> os.path.isfile('t.py')
True
>>> os.path.isfile('x.py')
False
2.os.path.isdir(path)
return True if path names a directory
3.os.path.getsize(path)
Return the size of the file in bytes
>>> os.path.getsize('c:\\users\\binuvp\\t.py')
111
4.os.path.exists(path)
Returns true if the file exists
>>> os.path.exists('t.py')
True
>>> os.path.exists('s.py')
False
When working with files in Python, there may be times when you need to check whether a file exists or not.Confirming the existence of a specific file comes in handy when you want to perform particular operations, such as opening, reading from, or writing to that file.
If you attempt to perform any of the operations mentioned above and the file doesn't exist, you will come across bugs and your program will end up crashing.
So, to perform operations and prevent your program from crashing, it is a helpful first step to check if a file exists on a given path.
Example:
import os.path path = './example.txt'
check_file = os.path.isfile(path)
print(check_file)
# output True if file exist
OR
import os.path path = './example.txt'
check_file = os.path.exists(path)
print(check_file)
# output
# True
sys Module
sys.exit()
Command-line arguments
Sample programs
1.The following program will count the number of files in the current directory.
import os
def countfiles(path):
count=0
lst=os.listdir(path)
for f in lst:
if os.path.isfile(f):
count=count+1
else:
os.chdir(f)
count=count+countfiles(os.getcwd())
os.chdir('..')
return count
c=countfiles('.')
print("number of files...=",c)
2.Print the names of the files in the current directory having ".py" extension.
import os
path=os.getcwd()
lst=os.listdir(path)
for f in lst:
if '.py' in f:
print(f)
Summary
The sys module provides functions and variables used to manipulate different parts of the Python runtime environment. The sys module provides information about constants, functions and methods of the Python interpreter.
The current version number of Python
>>> import sys
>>> sys.version
'3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)]'
>>> sys.version_info
sys.version_info(major=3, minor=8, micro=5, releaselevel='final', serial=0)
recursion limit
>>> sys.getrecursionlimit()
1000
search path for all Python modules
>>> sys.path
['C:\\Users\\binuvp\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\idlelib', 'C:\\Users\\binuvp\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\binuvp\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\binuvp\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\binuvp\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\binuvp\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages']
This causes the script to exit back to either the Python console or the command prompt. This is generally used to safely exit from the program in case of generation of an exception.
Name of the platform on which Python is running, e.g. "linux2" for Linux and "win32" for Windows
>>> sys.platform
'win32'
A string containing the name of the executable binary (path and executable file name) for the Python interpreter.
>>> sys.executable
'C:\\Users\\binuvp\\AppData\\Local\\Programs\\Python\\Python38-32\\pythonw.exe'
Lots of scripts need access to the arguments passed to the script, when the script was started. sys.argv is a list, which contains the command-line arguments passed to the script. The first item of this list contains the name of the script itself. The arguments follow the script name.
The following script iterates over the sys.argv list :
import sys
# it's easy to print this list of course:
print (sys.argv )
# or it can be iterated via a for loop:
for i in range(len(sys.argv)):
if i == 0:
print("Function name: " , sys.argv[0] )
else:
print("%d. argument: %s" % (i,sys.argv[i]) )
We save this script as arguments.py. If we call it, we get the following output::
$ python arguments.py arg1 arg2
['arguments.py', 'arg1', 'arg2']
Function name: arguments.py
1. argument: arg1
2. argument: arg2
Comments
Post a Comment