0% found this document useful (0 votes)
57 views34 pages

File Handling in Python Last Updated 25-04-2024 240426 180346

This file consists handling in python

Uploaded by

pallavi.baj05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views34 pages

File Handling in Python Last Updated 25-04-2024 240426 180346

This file consists handling in python

Uploaded by

pallavi.baj05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Department of Computer Science and Engineering (Artificial Intelligence & Machine Learning)

Python Programming – II Year B.Tech II Semester


Course Instructor: Prof.B.Sreenivasu, 9502251564, 9550411738
----------------------------------------------------------------------------------------------------------------------------------
Unit-II:
-----------------------------------------------------------------------------------------------------------------------------------------------------------
FILES: File Objects, File Built-in Function, File, File Built-in Attributes, Standard Files, command-
line arguments.
-----------------------------------------------------------------------------------------------------------------------------------------------------------
Exceptions: Exceptions in Python, Detecting and Handling Exceptions, Context
Management, *Exceptions as Strings, Raising Exceptions, Assertions, Standard Exceptions,
Creating Exceptions.
-----------------------------------------------------------------------------------------------------------------------------------------------------------
Modules: Importing Modules, Importing Module Attributes, Module Built-in Functions,
Packages.
-----------------------------------------------------------------------------------------------------------------------------------------------------------

FILE HANDLING IN PYTHON

Python File Open:


➢ File handling is an important part of any web application.
➢ Python has several functions for creating, reading, updating, and deleting files.
What is a file?
➢ A file is named memory location on external storage device.
➢ Files are used to store data permanently.
➢ The data stored in RAM or Main memory is not permanent.
Files are two types
1. Text file
2. Binary file

➢ In text file data is stored in text format or string format (OR) it allows only strings.
Example: .txt, .csv, .json,…
➢ Text Files: Text file allows only string data or text.

➢ In binary file data is stored in bytes format (OR) it allows only bytes type. Example:
images, audio, video, etc.
Basic steps to work with files:
1. Open File
2. Reading/Writing – performing operation
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 1 of 34
3. Close File

File Handling:
➢ The key function for working with files in Python is the open() function.

➢ The open() function takes two parameters (arguments) ; filename, and mode.

Syntax:
file_object = open(file_name, access_mode=’r’)
• the file name is string containing the name of the file to open.

There are four different modes for opening a file:

➢ "r" - Read - Default value. Opens a file for reading, error if the file does not exist

➢ "a" - Append - Opens a file for appending, creates the file if it does not exist

➢ "w" - Write - Opens a file for writing, creates the file if it does not exist

➢ "x" - Create - Creates the specified file, returns an error if the file exists
(In addition, you can specify if the file should be handled as binary or text mode)

➢ "t" - Text - Default value. Text mode

➢ "b" - Binary - Binary mode (e.g. images)

Character Meaning

'r' open for reading (default)

'w' open for writing, truncating the file first

'x' open for exclusive creation, failing if the file already exists

'a' open for writing, appending to the end of file if it exists

'b' binary mode

't' text mode (default)

'+' open for updating (reading and writing)

➢ wb : Write Binary
➢ rb : Read Binary
➢ wt : Write Text
➢ rt : Read Text
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 2 of 34
➢ w : Write Text
➢ r : Read Text
➢ r+w : update

To open a file for reading it is enough to specify the name of the file:
f1 = open("demofile.txt")
The code above is the same as:
f1 = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify
them.
Note: Make sure the file exists, or else you will get an error.

Python File Open:


Open a File on the Server:
▪ Assume we have the following file, located in the same folder as Python:
demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
welcome to the world of python.

▪ To open the file, use the built-in open() function.


▪ The open() function returns a file object, which has a read() method for reading the
content of the file:
Example:
f1 = open("demofile.txt", "r")
print(f1.read())

Note: If the file is located in a different location, you will have to specify the file path, like
this:

Example:
Open a file on a different location:
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 3 of 34
f2 = open("D:\\myfiles\welcome.txt", "r")
print(f2.read())

Read Only Parts of the File:


❖ By default the read() method returns the whole text, but you can also specify how
many characters you want to return:

Example:
# Return the 5 first characters of the file:
f2= open("demofile.txt", "r")
print(f2.read(5))

Read Lines:
❖ You can return one line by using the readline() method:

Example:
#Read one line of the file:
f3 = open("demofile.txt", "r")
print(f3.readline())

Note: By calling readline() two times, you can read the two first lines:
Example:
#Read two lines of the file
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())

Note:
By looping through the lines of the file, you can read the whole file, line by line:

Example:
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 4 of 34
#Loop through the file line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)

Close Files:
❖ It is a good programming practice to always close the file when you are done with
it.
Example:
# Close the file when you are finish with it:
f = open("demofile.txt", "r")
print(f.readline())
f.close()

Python File Write:


Write to an Existing File:
▪ To write to an existing file, you must add a parameter to the open() function:
▪ "a" - Append - will append to the end of the file
▪ "w" - Write - will overwrite any existing content
Example:
#Open the file "demofile2.txt" and append content to the file:
f5 = open("demofile2.txt", "a")
f5.write("Welcome to world of AIML”)
f5.close()

#open and read the file after the appending:


f6 = open("demofile2.txt", "r")
print(f6.read())

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 5 of 34
Example:
#Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w") # open() function returns file object
f.write("trying to overwrite the content")
f.close()

#open and read the file after the overwriting:


f = open("demofile3.txt", "r")
print(f.read())

Create a New File:


❖ To create a new file in Python, use the open() method, with one of the following
parameters:
❖ "x" - Create - will create a file, returns an error if the file exist
❖ "a" - Append - will create a file if the specified file does not exist
❖ "w" - Write - will create a file if the specified file does not exist

Example:
Create a file called "bs.txt":
f4 = open("bs.txt", "x")
print(“a new empty file is created”)
OUTPUT:
a new empty file is created

Example:
Create a new file if it does not exist:
f = open("myfile.txt", "w")

Python Delete File:


Delete a File:
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 6 of 34
❖ To delete a file, you must import the OS module, and run its os.remove() function:
Example:
#Remove the file "demofile.txt":
import os
os.remove("demofile.txt")

Check if File exist:


To avoid getting an error, you might want to check if the file exists before you try to delete
it:

Example:
Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")

Deleting Folder:
To delete an entire folder, use the os.rmdir() method:
Example:
Remove the folder "myfolder":
import os
os.rmdir("myfolder")
Note: You can only remove empty folders.

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 7 of 34
File handling in Python:
▪ Reading a file in Python can be done in a few ways.
▪ The most common way is to use the built-in function called open () function, which
returns a file object that can be used to read from the file.

Example python program for demonstrating how to read a file in Python:

with open('file.txt', 'r') as f:


data = f.read()

In this example, we are opening a file called "file.txt" in read mode ("r"). We are using a
"with" statement to ensure that the file is properly closed when we are done with it.

The "read" method is then called on the file object, which returns the contents of the file as
a string.

Writing to a file in Python is similar to reading from a file.


Here's an example of how to write to a file:

CODE:

with open('file.txt', 'w') as f:


f.write('Hello, world!')

In this example, we are opening a file called "file.txt" in write mode ("w"). We are using a
"with" statement to ensure that the file is properly closed when we are done with it.

The "write()" method is then called on the file object, which writes the string "Hello, world!"
to the file.

Appending to a file is also possible by using "a" mode instead of "w".


Here's an example of how to append to a file:

with open('file.txt', 'a') as f:


f.write('This is appended text.')

In this example, we are opening a file called "file.txt" in append mode ("a"). We are using
a "with" statement to ensure that the file is properly closed when we are done with it.

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 8 of 34
The "write" method is then called on the file object, which appends the string "This is
appended text." to the end of the file.

Key-note: It's important to note that when you open a file using the "open" function, you
can specify the mode in which you want to open the file (read, write, append, etc.).
Additionally, you can use the "close" method on the file object to manually close the file
once you're done with it, although using a "with" statement is generally preferred as it
automatically takes care of closing the file for you.

Note:
In Python, you can get information about a file's attributes (such as its size, modification
time, etc.) using the "os" module.

Here is an example program that demonstrates how to use the "os" module to get
information about a file:

Program:

import os
# Get the size of a file in bytes
size = os.path.getsize('file.txt')
print('File size:', size, 'bytes')

# Get the last modified time of a file


mod_time = os.path.getmtime('file.txt')
print('Last modified time:', mod_time)

In this example, we first import the "os" module.

We then use the "getsize" function from the "os.path" module to get the size of the file
"file.txt". This function returns the size of the file in bytes, which we store in the "size" variable
and print it out along with a message.

Next, we use the "getmtime" function from the "os.path" module to get the last modified
time of the file "file.txt". This function returns the time as a number of seconds since the
epoch, which we store in the "mod_time" variable and print it out along with a message.

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 9 of 34
Additionally, the "os" module provides a wide range of methods that allows you to get other
information about files on your system, such as the permissions set for the file or its owner.
These methods provide a powerful way to access and manipulate files in a Python
program.
-----------------------------------------------------------------------------------------------------------------------------------

File Built-in Attributes:


In Python, the built-in file object provides a number of attributes that allow you to get
information about files.
Here are some of the most common file attributes:
1. name - the name of the file
2. mode - the file access mode (e.g. 'r' for read, 'w' for write)
3. closed - whether or not the file is closed

Example python program - demonstrating how to access these file attributes in Python:
file = open('example.txt', 'r')
print('File name:', file.name)
print('File mode:', file.mode)
print('File closed?', file.closed)

-------------------------------------------------------------------------------------------------------

File Built-in Methods (BIMs) : BIFs

Method Description

read() Returns the file content

readline() Returns one line from the file

readlines() Returns a list of lines from the file

write() Writes the specified string to the file

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 10 of 34
writelines() Writes a list of strings to the file

Method Description

read() Returns the file content

readline() Returns one line from the file

readlines() Returns a list of lines from the file

write() Writes the specified string to the file

writelines() Writes a list of strings to the file

File Built-in Methods (BIMs) : tell() and seek()

▪ seek() function is used to change the file pointer to a given specific position.
▪ File pointer is like a cursor, which defines from where data has to be read or written
into the file.
▪ Syntax:
▪ Fileobj.seek(offset,from_what)
▪ The reference point is defined by the “from_what” argument. It can have any one
the following values.
▪ 0 : sets the reference point at the beginning of a file, which is by default.
▪ 1 : sets the reference point at the current file position.
▪ 2 : sets the reference point at the end of the file.

➢ Note: In Python 3.x and above, we can seek from beginning only, if opened in text
mode.
➢ We can overcome from this by opening the file in ‘b’ mode (Binary mode)
➢ tell()
➢ tell() returns the current position of the file pointer from the beginning of the file.

File Built-in Attributes:


Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 11 of 34
In Python, the built-in file object provides a number of attributes that allow you to get
information about files.
Here are some of the most common file attributes:

1. name - the name of the file


2. mode - the file access mode (e.g. 'r' for read, 'w' for write)
3. closed - whether or not the file is closed
4. encoding - the file encoding (if the file is opened in text mode)

Here's an example python program demonstrating how to access these file attributes in
Python:

file = open('example.txt', 'r')


print('File name:', file.name)
print('File mode:', file.mode)
print('File closed?', file.closed)

# Only available if file is opened in text mode


print('File encoding:', file.encoding)

In this example, we first open the file "example.txt" in read mode using the `open()` function
and store the resulting file object in the variable `file`.

We then access the `name`, `mode`, and `closed` attributes of the file object and print
their values.

Finally, we attempt to access the `encoding` attribute, which is only available if the file is
opened in text mode. If the file is not opened in text mode, attempting to access the
`encoding` attribute will result in an error.

By using these file object attributes, you can access and manipulate various properties of
files in your Python programs.

Example:
# Create a text file

f=open("f:\\file1.txt","w")
print("file created")
f.write("Python")

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 12 of 34
f.write("Java")
f.write("Oracle")
f.write("C#.Net")
f.write("65")
f.close()

Output:
file created

print() function

Example:
# Create a student file to store rollno,name,s1,s2

f=open("f:\\marks.txt","a")
while True:
rno=int(input("Rollno "))
name=input("Name ")
s1=int(input("Subject1 Marks "))
s2=int(input("Subject2 Marks "))
print(rno,name,s1,s2,file=f)
ch=input("Add another student?")
if ch=="no":
f.close()
break

Output:
Rollno 1
Name naresh
Subject1 Marks 60
Subject2 Marks 70
Add another student?yes
Rollno 2
Name suresh
Subject1 Marks 30
Subject2 Marks 40

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 13 of 34
Add another student?yes
Rollno 3
Name kishore
Subject1 Marks 60
Subject2 Marks 70
Add another student?yes
Rollno 4
Name ramesh
Subject1 Marks 80
Subject2 Marks 70
Add another student?yes
Rollno 5
Name rajesh
Subject1 Marks 99
Subject2 Marks 90
Add another student?no

Reading Data from Text file

read(size=- 1)
Read and return at most size characters from the stream as a single str. If size is negative
or None, reads until EOF (End Of File).

readline(size=- 1)
Read until newline or EOF and return a single str. If the stream is already at EOF, an empty
string is returned.
If size is specified, at most size characters will be read.

Example:
# Program to read content of file1.txt

f=open("f:\\file1.txt","r")
s=f.read()
print(s)
f.close()
f1=open("f:\\file1.txt","r")
s1=f1.read(2)

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 14 of 34
print(s1)
s2=f1.read(3)
print(s2)
s3=f1.read(2)
print(s3)
s4=f1.read(1)
print(s4)
f1.close()
Output:
PythonJavaOracleC#.Net65
Py
tho
nJ
a

Example:
# Program to read content of marks.txt

f=open("f:\\marks.txt","r")
while True:
stud=f.readline()
if stud==' ':
break
print(stud,end='')

f.close()

Output:
101 Naresh 60 70
102 Suresh 50 80
103 Rajesh 40 50
104 Kishore 30 40
1 naresh 60 70
2 suresh 30 40
3 kishore 60 70
4 ramesh 80 70
5 rajesh 99 90

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 15 of 34
Example:
# Read content from marks.txt
f=open("f:\\marks.txt","r")
while True:
stud=f.readline()
if stud=='':
break
list1=stud.split()
tot=int(list1[2])+int(list1[3])
avg=tot/2
result="pass" if int(list1[2])>=40 and int(list1[3])>=40 else "fail"
print(f'{list1[0]}\t{list1[1]}\t{list1[2]}\t{list1[3]}\t{tot}\t{avg:.2f}\t{result}')

Output:
101 Naresh 60 70 130 65.00 pass
102 Suresh 50 80 130 65.00 pass
103 Rajesh 40 50 90 45.00 pass
104 Kishore 30 40 70 35.00 fail
1 naresh 60 70 130 65.00 pass
2 suresh 30 40 70 35.00 fail
3 kishore 60 70 130 65.00 pass
4 ramesh 80 70 150 75.00 pass
5 rajesh 99 90 189 94.50 pass

Example:
# Write a program to copy content of one file to another file

file1=input("Enter File1 ")


file2=input("Enter File2 ")
f1=open(file1,"r")
f2=open(file2,"w")

s=f1.read()
f2.write(s)

f1.close()
f2.close()
print("File Copied")

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 16 of 34
Output:
Enter File1 f:\\marks.txt
Enter File2 f:\\marks1.txt
File Copied

CSV File or csv module

CSV stands for Comma Separated Values. CSV is a text file.


The so-called CSV (Comma Separated Values) format is the most common import and
export format for spreadsheets and databases
The csv module implements classes to read and write tabular data in CSV format. It allows
programmers to say, “write this data in the format preferred by Excel,” or “read data from
this file which was generated by Excel,” without knowing the precise details of the CSV
format used by Excel.

The csv module’s reader and writer objects read and write sequences. Programmers can
also read and write data in dictionary form using the DictReader and DictWriter classes.

csv.writer(csvfile)
Return a writer object responsible for converting the user’s data into delimited strings on the
given file-like object
Example:
# Creating csv file

import csv
f=open("f:\\emp.csv","w",newline='')
csvwr=csv.writer(f)
while True:
empno=int(input("EmployeeNo :"))
ename=input("EmployeeName :")
sal=float(input("Employee Salary :"))
csvwr.writerow([empno,ename,sal])
ch=input("Add another employee?")
if ch=="no":
f.close()
break

Output:
EmployeeNo :1
EmployeeName :naresh
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 17 of 34
Employee Salary :40000
Add another employee?yes
EmployeeNo :2
EmployeeName :suresh
Employee Salary :56000
Add another employee?yes
EmployeeNo :3
EmployeeName :kishore
Employee Salary :75000
Add another employee?no

writerow() method of write object convert list/sequence into comma separated values
string. This string is written side file using file object.

csv.reader(csvfile)
Return a reader object which will iterate over lines in the given csvfile. csvfile can be any
object which supports the iterator protocol and returns a string each time
its __next__() method is called.

Binary File

In binary file data is represented in byte format (OR) binary file is collection of bytes. It allows
reading and writing only bytes data.

Example: Image, Audio, Video,..

In order to work with binary files, the file must be opened in binary mode.

open(“file-name”,”wb”)

open(“file-name”,”rb”)

open(“file-name”,”w”)

Example:

# Creating binary file

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 18 of 34
f=open("f:\\file1.dat","wb")

f.write("Hello".encode())

b1=bytes(10)

f.write(b1)

b2=bytes(range(65,70))

f.write(b2)

f.close()

Output:

Data is written inside file1.dat

Example:

# Write a program to read content of one image

# and store inside another image

image_file1=input("Enter Image File Name ")

image_file2=input("Enter Dest Image File Name ")

f1=open(image_file1,"rb")

f2=open(image_file2,"wb")

data=f1.read()

f2.write(data)

print("Image is copied..")

f1.close()

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 19 of 34
f2.close()

Output:

Enter Image File Name dhoni.png

Enter Dest Image File Name dhonicopy.png

Image is copied..

--------------------------------------------------------------------------------------------------------------------------------
Python Command Line Arguments
❖ Python Command line arguments are input arguments(parameters) passed to the
python program(script) when executing them.
❖ Command line arguments are arguments which are given after name of the
program from command shell of operating system is called “Command line
arguments”

Python Command Line Arguments:


❖ There are many options to read python command line arguments (parameters). The
three most common ones are:
❖ In Python module ‘sys’ has variable called ‘argv’
❖ ‘argv’ in ‘sys’ module contains list of command line arguments.
python sys.argv Note: ‘argv’ is built-in variable(attribute) in module called ‘sys’

python getopt module


python argparse module

Python sys module


Python sys module contains ‘argv’ stores the command line arguments into a list, we can access it
using sys.argv. This is very useful and simple way to read command line arguments as String. Let’s look at a
simple example to read and print command line arguments using python sys module.

In sys module there is a built-in variable / attribute called argv ➔ command line arguments ➔ data
type of this variable is list.

#python program to read and print command line arguments


import sys
# argv is a attribute(variable) defined in sys module
# type of argv is a list
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 20 of 34
print(type(sys.argv))
print("length of command line arguments: ",len(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)

OUTPUT:
C:\Users\Sreenivasu\Desktop>cmdargs0.py # using command prompt
<class 'list'>
length of command line arguments: 1
The command line arguments are:

The above figure is showing python program named as cmdargs0.py can be executed
from system command prompt.

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 21 of 34
Figure shows on desktop we have a python program(file) named as ‘cmdargs0’ which is
saved with an extension .py

#python program to read and print command line arguments


import sys
# argv is a attribute(variable) defined in sys module
# type of argv is a list
print(type(sys.argv))
print("length of command line arguments: ", len(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)

OUTPUT: (Observe it in below screen shot)


C:\Users\Sreenivasu\Desktop>cmdargs0.py 10 20 30 40 50
<class 'list'>
length of command line arguments: 6
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 22 of 34
The command line arguments are:
C:\Users\Sreenivasu\Desktop\cmdargs0.py
10
20
30
40
50

Executing python program(script) named as cmdargs1.py from system command


prompt

For your understanding screen shot is included here.

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 23 of 34
# python program to get length of command line arguments
import sys

arguments = sys.argv[1:] # reading command line arguments excluding python program(script) name

print(len(arguments)) # Count the length of the arguments

# Print the result


print(f"Number of command line arguments: {arguments}")

# arguments = sys.argv[1:] #data type of variable argv is list. Hence to read elements in a
list we are using slicing

OUTPUT:
C:\Users\Sreenivasu>cd desktop

C:\Users\Sreenivasu\Desktop>cmdargs1.py
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 24 of 34
0
Number of command line arguments: []

C:\Users\Sreenivasu\Desktop>cmdargs1.py 20 25 46 80 90
5
Number of command line arguments: ['20', '25', '46', '80', '90']

Note: screen shots included here for your better understanding of command line
arguments.

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 25 of 34
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 26 of 34
Name of the python program is ‘cmdargs2.py’

#python program to read and print command line arguments

from sys import argv #from sys module import built-in variable called argv
print("type of argv: ",type(argv))
print("the length of variable 'argv' in sys module:",len(argv))
for x in argv:
print(x)

OUTPUT:
C:\Users\Sreenivasu>cd desktop

C:\Users\Sreenivasu\Desktop>cmdargs2.py
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 27 of 34
type of argv: <class 'list'>
the length of variable 'argv' in sys module: 1
C:\Users\Sreenivasu\Desktop\cmdargs2.py

C:\Users\Sreenivasu\Desktop>cmdargs2.py 10 20 30 40 50
type of argv: <class 'list'>
the length of variable 'argv' in sys module: 6
C:\Users\Sreenivasu\Desktop\cmdargs2.py
10
20
30
40
50

#write a python program with command line argument to count the length of
the arguments
import sys

print("data type of argv built-in variable in sys module: ",type(sys.argv))


print("length of the command line arguments: ",len(sys.argv))

OUTPUT:
C:\Users\Sreenivasu>cd desktop

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 28 of 34
C:\Users\Sreenivasu\Desktop>cmdargs3.py #from system command prompt

data type of argv built-in variable in sys module: <class 'list'>


length of the command line arguments: 1

C:\Users\Sreenivasu\Desktop>cmdargs3.py 10 20 30 45 #from system command prompt

data type of argv built-in variable in sys module: <class 'list'>


length of the command line arguments: 5

Note: In command line arguments name of python program is also one element in ‘argv’
variable which is a list.

Executing python program from system command prompt and passing


arguments(parameters) to python program from command line prompt.

Steps:

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 29 of 34
Note we have saved our python program on desktop with the name ‘cmdargs3.py’

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 30 of 34
#Write a python program to Sum up all Given inputs using command line
arguments.

from sys import argv


print("data type of variable 'argv' which is a built-in variable in 'sys' module: ",type(argv))
args_list=argv[1:] #args_list==> arguments list
sum=0
for x in args_list:
sum=sum+x

print("sum of arguments is: ",sum)

OUTPUT:
C:\Users\Sreenivasu\Desktop>cmdargs4.py
data type of variable 'argv' which is a built-in variable in 'sys' module: <class 'list'>

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 31 of 34
sum of arguments is: 0

C:\Users\Sreenivasu\Desktop>cmdargs4.py 10 25 45 50
data type of variable 'argv' which is a built-in variable in 'sys' module: <class 'list'>
Traceback (most recent call last):
File "C:\Users\Sreenivasu\Desktop\cmdargs4.py", line 8, in <module>
sum=sum+x
~~~^~
TypeError: unsupported operand type(s) for +: 'int' and 'str'

#Write a python program to Sum up all Given inputs using command line
arguments.

from sys import argv


print("data type of variable 'argv' which is a built-in variable in 'sys' module: ",type(argv))
args_list=argv[1:] #args_list==> arguments list
sum=0
for x in args_list:
sum=sum+int(x) #note=> every argument passed to python program
from command prompt is a string

print("sum of arguments is: ",sum)

#note=> every argument passed to python program from command prompt is a string
#hence type conversion is required string object must be converted into int object.

OUTPUT:
C:\Users\Sreenivasu\Desktop>cmdargs4.py 10 20 35 40
data type of variable 'argv' which is a built-in variable in 'sys' module: <class 'list'>
sum of arguments is: 105

#Write a python program to Sum up all Given inputs using command line arguments.

from sys import argv


print("data type of variable 'argv' which is a built-in variable in 'sys' module: ",type(argv))
args_list=argv[1:] #args_list==> arguments list
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 32 of 34
sum=0
for x in args_list:
sum=sum+int(x) #note=> every argument passed to python program
from command prompt is a string

print("sum of arguments is: ",sum)


print("length of command line arguments: ",len(argv))

#note=> every argument passed to python program from command prompt is a string
#hence type conversion is required

OUTPUT:
C:\Users\Sreenivasu\Desktop>cmdargs4.py 1 2 3 4 50 60
data type of variable 'argv' which is a built-in variable in 'sys' module: <class 'list'>
sum of arguments is: 120
length of command line arguments: 7

KEYNOTE:

Python sys module has variable called ‘argv’ stores the command line arguments into a list, we can
access it using sys.argv.
This is very useful and simple way to read command line arguments as String.

argv is a built-in variable in sys module.

Data type of argv is list

Look at the following example:

C:\Users\Sreenivasu\Desktop>cmdargs4.py 1 2 3 4 50 60
data type of variable 'argv' which is a built-in variable in 'sys' module: <class 'list'>
sum of arguments is: 120
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 33 of 34
length of command line arguments: 7

argv is list ===>


List elements cmdargs4.py 1 2 3 4 50 60
60 60 60 60 60 60 60
List index positions

Remember & observe the output in above program number of arguments which passed
to python program(script) from command prompt is 6 only. But if you look at the output
length of command line arguments is : 7 which means in argv list python program(script
name) is also one command line argument which is present in argv list in index position 0.

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 34 of 34

You might also like