0% found this document useful (0 votes)
49 views48 pages

Problem Solving Using Python (ITFC0101) : File Handling, Command Line Arguments, Errors and Exceptions

The document discusses file handling in Python including opening, reading, and writing to files. It covers opening files in different modes, using methods like read(), write(), and close(). It also discusses command line arguments using sys.argv and handling errors and exceptions in programs.

Uploaded by

devanbansal777
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)
49 views48 pages

Problem Solving Using Python (ITFC0101) : File Handling, Command Line Arguments, Errors and Exceptions

The document discusses file handling in Python including opening, reading, and writing to files. It covers opening files in different modes, using methods like read(), write(), and close(). It also discusses command line arguments using sys.argv and handling errors and exceptions in programs.

Uploaded by

devanbansal777
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/ 48

Problem Solving using Python

(ITFC0101)
File Handling, Command Line Arguments, Errors and Exceptions

Dr. Naveen Kumar Gupta

Assistant Professor
Department of Information Technology
Dr B R Ambedkar National Institute of Technology Jalandhar
1
Why File Handling?

• Interaction with user Till now: Take input from console and write output back to the
console

Issues with console based approach

• Volatile memory: data removed after execution so need to store data for future use
• Large amount of data as input and output may possible
• Difficult to manually provide large amount of data to the program
• Difficult to handle large amount output data
2
Why File Handling?

Solution

• File handling offers data to be stored permanently into the file (non-volatile)
• File may be used as input and output
• Two formats of files in python
• Text
• Binary

3
• Python interpreter reads the file line by line
• Each line of code includes a sequence of characters and they form a text file
• The line of a file is terminated with a special character:
• EOL or End of Line
• characters like comma {,} or newline character

4
Advantages of File Handling

• Versatility: Perform a wide range of operations:


• creating, reading, writing, appending, renaming, and deleting files
• Flexibility: Allows to work with different file formats
• text files, binary files, CSV files, etc.
• User–friendly: Easy to create, read, and manipulate files
• Cross-platform: file-handling functions work across different platforms
• e.g. Windows, Mac, Linux
5
Problems with File Handling

• Error-prone: May provide errors if


• code is not carefully written
• Issues with the file system (e.g. file permissions, file locks, etc.).
• Security risks:
• Can be used to access or modify sensitive files on the system
• Complexity:
• Complex if new file formats or operations introduced
• Performance: File handling operations in Python can be slower than other programming
languages
6
Sequence of operations in File

• Open a file
• Create a new file if not exist
• Read or write - Performing operation
• Close the file

7
Open a file
Syntax: f = open(filename, mode) // f file pointer
Following mode is supported:

• r: open an existing file for a read operation


• If the file does not exists raises I/O error

• w: open an existing file for a write operation


• If the file already contains some data it will be overridden

• If the file is not present it creates the file

• a: open an existing file for append operation


• Append the data the end
• It won’t override existing data
8
Open a file
Syntax: f = open(filename, mode) // f file pointer
Following mode is supported:

• r+: To read and write data into the file


• If the file does not exists raises I/O error

• Override existing data


• w+: To write and read data
• It will override existing data
• a+: To append and read data from the file
• File created if doesn’t exist
9
Read file and Print
r mode

file = open(‘abc.txt', 'r') file = open(“abc.txt", "r")


for each in file: print (file.read())
print (each) file.close()
file.close()

10
Write data in file
w mode

file = open(‘abc.txt','w')

file.write("This is the write command")

file.write("It allows us to write in a particular file")

file.close()

11
Write data in file
a mode

file = open(‘abc.txt',’a')

file.write("This will add this line in append mode")

file.close()

12
File Handling Methods

Methods Description

close() Closes the file

detach() Returns the separated raw stream from the buffer


Returns a number that represents the stream, from the operating
system's perspective
fileno()
flush() Flushes the internal buffer

isatty() Returns whether the file stream is interactive or not

read() Returns the file content


13
File Handling Methods
Methos Description
readable() Returns whether the file stream can be read or not
readline() Returns one line from the file
readlines() Returns a list of lines from the file
seek() Change the file position
seekable() Returns whether the file allows us to change the file position
tell() Returns the current file position
truncate() Resizes the file to a specified size
writable() Returns whether the file can be written to or not
write() Writes the specified string to the file
writelines() Writes a list of strings to the file
14
Command Line Arguments

15
Command Line Arguments
Used in script mode of program execution

• Given after name of the program in command line shell (cmd/ Terminal)
• Ways to deal with command line arguments are:

1. Using sys.argv

2. Using getopt module

3. Using argparse module

16
Procedure to execute program with command
line arguments
• Write program in script mode
• Save the script with some name, say: abc.py
• Execute the program using command line: python abc.py
• Here, abc.py is the first argument
• To take more such arguments
python abc.py ‘Hello’ ‘hi’ 1 556 234
nd rd
Here, 2 argument Hello 3 argument hi
th th
4 argument 1 5 argument 556 and so on
17
Command Line Arguments
Using sys.argv
sys module:

• Provides functions and variables used to manipulate different parts of Python


runtime environment

• Provides access to some


• Variables used or maintained by the interpreter
• Functions that interact strongly with the interpreter

• One such variable is: sys.argv 18


Command Line Arguments
Using sys.argv
sys module:

• sys.argv is a simple list structure

Main purpose of sys.argv are:

• List of command line arguments


• len(sys.argv): number of command line arguments

• sys.argv[0]: name of the current Python script


19
Program to compute the sum of all command line arguments

import sys for i in range(1, n):

# total arguments print(sys.argv[i], end = " ")

n = len(sys.argv) Sum = 0

print("Total arguments passed:", n)

# Arguments passed for i in range(1, n):

print("\nName of script:", sys.argv[0]) Sum += int(sys.argv[i])

print("\nArguments passed:", end = " ") print("\n\nResult:", Sum)

Save file: cmdsum.py Run file: python sum.py 22 43 65 77 31


20
Output

21
Command Line Arguments
Using getopt module

• Extends the separation of the input string by parameter validation

• Allows both short, and long options including a value assignment

• Requires the use of the sys module to process input data properly

• Required to remove first element from the list of command-line arguments


22
Command Line Arguments (getopt)
Syntax: getopt.getopt(args, options, [long_options])
Parameters:

• args: List of arguments to be passed


• options: String of option letters that the script want to recognize. Options that require
an argument should be followed by a colon (:).

• long_options: List of string with the name of long options. Options that require
arguments should be followed by an equal sign (=).

• Return Type: 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.
23
Command Line arguments
Using argparse module

• A better option than sys.argv and getopt


• Provides rich options:
• positional arguments
• default value for arguments
• help message
• specifying data type of argument
• And many more 24
Error and Exceptions

25
Error and Exceptions

Error:

• Problems in a program due to which the program will stop the execution
• Prevents the program from completing its task
Exceptions:

• Some internal events occur which changes normal flow of program


• A condition that interrupts the normal flow of the program

Both errors and exceptions occur during the execution of a program


26
Error and Exceptions

Two types of Error occurs in python:

• Syntax errors
• Logical errors (Exceptions)

27
Syntax errors
When the proper syntax of the language is not followed then a syntax
error is thrown

28
Logical errors (Exceptions)

When in the runtime an error that occurs after passing the syntax test is called exception
or logical type

Example:

• when divide any number by zero then the ZeroDivisionError exception


• when import a module that does not exist then ImportError is raised

29
30
Common Error and Exceptions
Exception Description
IndexError When the wrong index of a list is retrieved
AssertionError It occurs when the assert statement fails
AttributeError It occurs when an attribute assignment is failed
ImportError It occurs when an imported module is not found
KeyError It occurs when the key of the dictionary is not found
NameError It occurs when the variable is not defined
MemoryError It occurs when a program runs out of memory
It occurs when a function and operation are applied in an
TypeError
incorrect type 31
Common Error and Exceptions
• ValueError: This exception is raised when a function or method is called with an
invalid argument or input, such as trying to convert a string to an integer when the
string does not represent a valid integer.

• AttributeError: This exception is raised when an attribute or method is not found on


an object, such as trying to access a non-existent attribute of a class instance.

• IOError: This exception is raised when an I/O operation, such as reading or writing a
file, fails due to an input/output error.

• ZeroDivisionError: This exception is raised when an attempt is made to divide a


number by zero.

• ImportError: This exception is raised when an import statement fails to find or load a
module.

32
Exception Handling

33
Exception Handling

Exception is the base class for all the exceptions in Python

34
Catching Exceptions
Try and Except Statement

• Used to catch and handle exceptions in Python


• Statements that can raise exceptions are kept inside the try clause
• Statements that handle the exception are written inside except clause

• Example:
• Access the array element whose index is out of bound
• Handle the corresponding exception 35
36
Catching Specific Exception

• A try statement can have more than one except clause


• Used to specify handlers for different exceptions
• At most one handler will be executed

• Example
• add IndexError in the previous code

37
Catching Specific Exception
Syntax

try:

# statement(s)

except IndexError:

# statement(s)

except ValueError:

# statement(s)

38
39
Try with Else Clause

• In python, can use else clause on the try-except block


• Must be present after all the except clauses
• The code enters the else block only if the try clause does not raise an exception

40
Else executed
Except executed
41
Finally Keyword in Python

• Always executed after the try and except blocks

• Either, after the normal termination of the try block


or

• After the try block terminates due to some exception

42
Finally Keyword in Python
Syntax
try:

# Some Code....

except:

# optional block

# Handling of exception (if required)

else:

# execute if no exception. This may or may not be present

finally:

# Some code .....(always executed)


43
Finally Keyword in Python

44
Raising Exception

45
Advantages of Exception Handling
• Improved program reliability: By handling exceptions properly, you can prevent
your program from crashing or producing incorrect results due to unexpected errors or
input.

• Simplified error handling: Exception handling allows you to separate error handling
code from the main program logic, making it easier to read and maintain your code.

• Cleaner code: With exception handling, you can avoid using complex conditional
statements to check for errors, leading to cleaner and more readable code.

• Easier debugging: When an exception is raised, the Python interpreter prints a


traceback that shows the exact location where the exception occurred, making it easier
to debug your code.

46
Disadvantages of Exception Handling
• Performance overhead: Exception handling can be slower than using conditional
statements to check for errors, as the interpreter has to perform additional work to
catch and handle the exception.

• Increased code complexity: Exception handling can make your code more complex,
especially if you have to handle multiple types of exceptions or implement complex
error handling logic.

• Possible security risks: Improperly handled exceptions can potentially reveal


sensitive information or create security vulnerabilities in your code, so it’s important
to handle exceptions carefully and avoid exposing too much information about your
program.

47
Thank You!

48

You might also like