0% found this document useful (0 votes)
3 views

FILE 2

The document explains how to manage directories in Python using the os module, detailing methods such as mkdir(), chdir(), getcwd(), and rmdir(). It also covers command-line arguments, including the use of the sys module to access arguments and the getopt module for parsing options. Examples are provided for each method and command-line usage to illustrate their functionality.

Uploaded by

kitpandiarajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

FILE 2

The document explains how to manage directories in Python using the os module, detailing methods such as mkdir(), chdir(), getcwd(), and rmdir(). It also covers command-line arguments, including the use of the sys module to access arguments and the getopt module for parsing options. Examples are provided for each method and command-line usage to illustrate their functionality.

Uploaded by

kitpandiarajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

 Problem Solving And Python Programming 

5.3.3 Directories in Python

All files are contained within various directories, and Python has no
problem handling these too. The os module has several methods that help
you create, remove, and change directories, they are:
a) mkdir()
b) chdir()
c) getcwd()
d) rmdir()
a) The mkdir() Method
This mkdir() method of the os module to create directories in the
current directory. You need to supply an argument to this method which
contains the name of the directory to be created.
Syntax
os.mkdir(“newdir”)

Example

Following is the example to create a directory test in the current


directory −
import os
# Create a directory “test”
os.mkdir(“test”)
 Files 5.17

b) The chdir() Method


This chdir() method to change the current directory. The chdir()
method takes an argument, which is the name of the directory that you
want to make the current directory.
Syntax
os.chdir(“newdir”)

Example

Following is the example to go into “/home/newdir” directory −


import os
# Changing a directory to “/home/newdir”
os.chdir(“/home/newdir”)

c) The getcwd() Method


The getcwd() method displays the current working directory.

Syntax
os.getcwd()

Example
import os
# This would give location of the current directory
os.getcwd()

d) The rmdir() Method


This rmdir() method deletes the directory, which is passed as an
argument in the method.

Before removing a directory, all the contents in it should be


removed.

Syntax:
os.rmdir(‘dirname’)
 Problem Solving And Python Programming 

Example

To remove “/tmp/test” directory. It is required to give fully qualified


name of the directory, otherwise it would search for that directory in the
current directory.
import os
# This would remove “/tmp/test” directory.
os.rmdir( “/tmp/test” )

5.4 COMMAND LINE ARGUMENTS


Command-line options and arguments:
Python provides a getopt module that helps you parse command-
line options and arguments.

$ python test.py arg1 arg2 arg3

The Python sys module provides access to any command-line arguments


via the sys.argv. This serves two purposes, they are:

 sys.argv is the list of command-line arguments.

 len(sys.argv) is the number of command-line arguments.

Here sys.argv[0] is the program ie. script name.

Example

Consider the following script test.py


import sys
print ‘Number of arguments:’, len(sys.argv), ‘arguments.’
print ‘Argument List:’, str(sys.argv)
Now run above script as follows,
$ python test.py arg1 arg2 arg3
 Files 5.19

Output
Number of arguments: 4 arguments.

Argument List: [‘test.py’, ‘arg1’, ‘arg2’, ‘arg3’]

Note:
As mentioned above, first argument is always script name and it is
also being counted in number of arguments.

5.4.1 Parsing Command-Line Arguments

Python provided a getopt module that helps you parse command-


line options and arguments. This module provides two functions and an
exception to enable command line argument parsing.

 getopt.getopt method

This method parses command line options and parameter list.

Syntax
getopt.getopt(args, options, [long_options])

Here is the detail of the parameters:

 args: This is the argument list to be parsed.

 options: This is the string of option letters that the script wants
to recognize, with options that require an argument should be
followed by a colon (:).

 long_options: This is optional parameter and if specified, must be


a list of strings with the names of the long options, which should
be supported. Long options, which require an argument should be
followed by an equal sign (‘=’). To accept only long options, options
should be an empty string.

 This method returns value consisting of two elements: the first is


a list of (option, value) pairs. The second is the list of program
arguments left after the option list was stripped.
 Problem Solving And Python Programming 

 Each option-and-value pair returned has the option as its first


element, prefixed with a hyphen for short options (e.g., ‘-x’) or two
hyphens for long options (e.g., ‘--long-option’).

Exception getopt.Getopt Error


This is raised when an unrecognized option is found in the argument
list or when an option requiring an argument is given none.

The argument to the exception is a string indicating the cause of


the error. The attributes msg and opt give the error message and related
option

Example
Consider we want to pass two file names through command line and
we also want to give an option to check the usage of the script. Usage of
the script is as follows.

usage: test.py -i <inputfile> -o <outputfile>

Here is the following script to test.py


import sys, getopt
def main(argv):
inputfile = ‘’
outputfile = ‘’
try:
opts, args = getopt.getopt(argv,“hi:o:”,[“ifile=”,”ofile=”])
except getopt.GetoptError:
print ‘test.py -i <inputfile> -o <outputfile>’
sys.exit(2)
for opt, arg in opts:
if opt == ‘-h’:
print ‘test.py -i <inputfile> -o <outputfile>’
sys.exit()
elif opt in (“-i”, “--ifile”):
 Files 5.21

inputfile = arg
elif opt in (“-o”, “--ofile”):
outputfile = arg
print ‘Input file is “’, inputfile
print ‘Output file is “’, outputfile

if __name__ == “__main__”:

main(sys.argv[1:])

Now, run above script as follows,


$ test.py -h
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i BMP -o
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i inputfile
Input file is “ inputfile
Output file is “

Many programs can be run to provide you with some basic informa-
tion about how

they should be run. Python enables you to do this with -h:


$ python –h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit

You might also like