You are on page 1of 114

PYTHON PROGRAMMING

by C. RAJEEV
C. RAJEEVAssistant Professor,
Assist. Prof.Department of CSE,
Dept. of. CSE,
MRECW
MRECW.
UNIT IV
Python Functions, Advantage of Functions in Python, Creating a Function, Function Calling,
Parameters in Function, Call by Reference in Python, Types of Arguments, Required Arguments,
Keyword Arguments, Default Arguments, Variable-Length Arguments, Scope of Variables,
Python Built-in Functions, Python Lambda Functions, String with Functions, Strings Indexing
and Splitting, String Operators, Python Formatting Operator, Built-in String Functions, Python
File Handling, Opening a File, Reading the File, Read Lines of the File, Looping through the
File, Writing the File, Creating a New File Using with Statement with Files, File Pointer
Position, Modifying File Pointer Position Renaming the File & Removing the File, Writing
Python Output to the Files File Related Methods, Python Exceptions, Common Exceptions,
Problem without Handling Exceptions, except Statement with no Exception, Declaring Multiple
Exceptions, Finally Block, Raising Exceptions, Custom Exception,
1. Functions in Python
A function is a set of statements that take inputs, do some specific computation and
produces output.

The idea is to put some commonly or repeatedly done task together and make a
function, so that instead of writing the same code again and again for different inputs, we
can call the function.

Python also provides built-in functions like print(), etc. but we can also create your own
functions. These functions are called user-defined functions.
2. Creating a function:
We can create function using def keyword

Syntax of Function

def function_name(parameters):
"""docstring""“
statement(s)
Above shown is a function definition that consists of the following components.

Keyword def that marks the start of the function header.

A function name to uniquely identify the function. Function naming follows the

same rules of writing identifiers in Python.

Parameters (arguments) through which we pass values to a function. They are optional.

A colon (:) to mark the end of the function header.


Optional documentation string (docstring) to describe what the function does.

One or more valid python statements that make up the function body. Statements

must have the same indentation level (usually 4 spaces).

An optional return statement to return a value from the function.

Example of a function
def greet(name):
""" This function greets to the person
passed in as a parameter """
print("Hello Good morning!")
Docstrings
The first string after the function header is called the docstring and is short for
documentation string. It is briefly used to explain what a function does.

Although optional, documentation is a good programming practice. Unless you can


remember what you had for dinner last week, always document your code.
In the above example, we have a docstring immediately below the function header. We
generally use triple quotes so that docstring can extend up to multiple lines. This string is
available to us as the __doc__ attribute of the function.
For example:
Try running the following into the Python shell to see the output.
>>> print(greet.__doc__)
This function greets to
the person passed in as
a parameter
3.Function calling
How to call a function in python?
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.
>>> greet('Paul')
Hello, Paul. Good morning!
Ex:
def greet(name):
""" This function greets to the
person passed in as a parameter """
print("Hello, " + name + ". Good morning!")
greet('Paul')
The return statement
The return statement is used to exit a function and go back to the place from where it was
called.
Syntax of return
return [expression_list]
This statement can contain an expression that gets evaluated and the value is
returned.
If there is no expression in the statement or the return statement itself is not present
inside a function, then the function will return the None object.
For example:
>>> print(greet("May"))
Hello, May. Good morning!
None
Here, None is the returned value since greet() directly prints the name and no return statement is
used.
Example of return How Function works in Python?
def absolute_value(num):
"""This function returns the
absolute value of the entered
number""“
if num >= 0:
return num
else:
return –num
print(absolute_value(2))
print(absolute_value(-4))

Output
2
4
4. Parameters in Function:
In Python, you can define a function that takes variable number of arguments.
Ex:
def greet(name, msg):
"""This function greets to
the person with the provided
message"""
print("Hello", name + ', ' + msg)

greet("Monica", "Good morning!")


Output
Hello Monica, Good morning!

Here, the function greet() has two parameters. Since we have called this function with two
arguments, it runs smoothly and we do not get any error.
If we call it with a different number of arguments, the interpreter will show an error
message.

Below is a call to this function with one and no arguments along with their respective error
messages.

>>> greet("Monica") # only one argument

TypeError: greet() missing 1 required positional argument: 'msg‘

>>> greet() # no arguments

TypeError: greet() missing 2 required positional arguments: 'name' and 'msg'


5. Call by reference in Python :

In Python, call by reference means passing the actual value as an argument in the function.
All the functions are called by reference, i.e., all the changes made to the reference inside
the function revert back to the original value referred by the reference.

All parameters (arguments) in the Python language are passed by reference. It means if
you change what a parameter refers to within a function, the change also reflects back in the
calling function.
For example ,
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4])
print("Values inside the function: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme(mylist)
print("Values outside the function: ", mylist)
•Here, we are maintaining reference of the passed object and appending values in the same
object.
•So, this would produce the following result −
Output:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the reference is being overwritten
inside the called function.
For example,
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print("Values inside the function: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print("Values outside the function: ", mylist)
•The parameter mylist is local to the function changeme. Changing mylist within the function does not affect
mylist.
•The function accomplishes nothing and finally this would produce the following result –
Output:
Values inside the function: [1, 2, 3, 4]
6. Types of Arguments:
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed into a function.
From a function's perspective:
•A parameter is the variable listed inside the parentheses in the function definition.
• An argument is the value that are sent to the function when it is called.
There are three types of Python arguments:
•Default Arguments
•Keyword Arguments
•Arbitrary Arguments
1. Default Arguments:
•Function arguments can have default values in Python.
•We can provide a default value to an argument by using the assignment operator (=).
Here is an example:
def greet(name, msg="Good morning!"):
"""
This function greets to the person with the provided message. If the message is not provided, it
defaults to "Good morning!"
"""
print("Hello", name + ', ' + msg)
greet("Python")
greet(“python”, “programming”)
Output:
Hello Python, Good morning!
Hello Python, programming
•In this function, the parameter name does not have a default value and is required (mandatory)
during a call.

•On the other hand, the parameter msg has a default value of "Good morning!". So, it is optional
during a call. If a value is provided, it will overwrite the default value.

•Any number of arguments in a function can have a default value. But once we have a default
argument, all the arguments to its right must also have default values.

•This means to say, non-default arguments cannot follow default arguments. For example, if we
had defined the function header above as:

def greet(msg = "Good morning!", name):


We would get an error as:
SyntaxError: non-default argument follows default argument
2. Python Keyword Arguments
When we call a function with some values, these values get assigned to the arguments
according to their position.

For example, in the above function greet(), when we called it as greet("Bruce", "How do
you do?"), the value "Bruce" gets assigned to the argument name and similarly "How do
you do?" to msg. Python allows functions to be called using keyword arguments.

When we call functions in this way, the order (position) of the arguments can be changed.
Following calls to the above function are all valid and produce the same result.

Program:
# 2 keyword arguments
greet(name = "Bruce",msg = "How do you do?")
# 2 keyword arguments (out of order)
greet(msg = "How do you do?",name = "Bruce")
1 positional, 1 keyword argument
greet("Bruce", msg = "How do you do?")

Output:
Hello Bruce, How do you do?
Hello Bruce, How do you do?
Hello Bruce, How do you do?

As we can see, we can mix positional arguments with keyword arguments during a function
call. But we must keep in mind that keyword arguments must follow positional arguments.

Having a positional argument after keyword arguments will result in errors.


For example, the function call as follows:
greet(name="Bruce","How do you do?")
Will result in an error:
SyntaxError: non-keyword arg after keyword arg
3,.Python Arbitrary Arguments
Sometimes, we do not know in advance the number of arguments that will be passed into
a function.
Python allows us to handle this kind of situation through function calls with an arbitrary
number of arguments.
In the function definition, we use an asterisk (*) before the parameter name to denote this
kind of argument.

Here is an example.
def greet(*names): Output:
"""This function greets all the Hello Monica
person in the names tuple.""“ Hello Luke
# names is a tuple with arguments Hello Steve
for name in names: Hello John
print("Hello", name)
greet("Monica", "Luke", "Steve", "John")
7. Variable-Length Arguments in Python:
Some functions have no arguments, others have multiple. There are times we have
functions with arguments we don't know about beforehand.
We may have a variable number of arguments because we want to offer a flexible API to
other developers or we don't know the input size.
 With Python, we can create functions to accept any amount of arguments. These
functions can accept an unknown amount of input, either as consecutive entries or named
arguments.
In the following Python program we are calling a function and passing two integer values
and it is returning back the sum.
# func
def sum(x, y):
return x + y
result = sum(10, 20)
print(result) # 30
So, the above code will print 30 as output.
Now, imagine we want to create a sum function that can take any number of arguments (like 2,
3, 4 ...).The problem with above sum function is that we can only pass two arguments.

Python allows us to create functions that can take multiple arguments. So, lets create multi-
argument functions.

Following is the syntax to create a function that can take variable length arguments.
def func(*args):
# body of the function
Where, func is the name of the function and *args holds variable length arguments.
Passing multiple arguments:
In the following Python program we are recreating the sum function but this time we are
modifying it to take multiple arguments and print them.

Program: Output:

def sum(*args): <class 'tuple'>

print(type(args)) (10, 20)

print(args) <class 'tuple'>

sum(10, 20) (10, 20, 30)

sum(10, 20, 30) <class 'tuple'>

sum(10, 20, 30, 40) (10, 20, 30, 40)

So, we can see that the args variable is of type tuple and we are also able to print all the values
that were passed to the function as a tuple.1
Accessing multiple arguments:
Since the multiple arguments passed to the function are tuple so we can access them using
for loop. In the following Python program we are printing out the individual argument.
Program:
def sum(*args):
The above code will given us the following output.
for arg in args: sum(10, 20)
print(arg) 10
20
print('sum(10, 20)') sum(10, 20, 30)
sum(10, 20) 10
20
print('sum(10, 20, 30)') 30
sum(10, 20, 30) sum(10, 20, 30, 40)
10
print('sum(10, 20, 30, 40)') 20
sum(10, 20, 30, 40) 30
40

So, now that we are able to access the individual argument passed to the function let's go ahead
and modify the sum function that we are working on to return us the sum of the arguments.
Multiple arguments sum function:
Program:
def sum(*args):
result = 0
for arg in args:
result = result + arg
return result
print(sum(10, 20)) # 30
print(sum(10, 20, 30)) # 60
print(sum(10, 20, 30, 40)) # 100
Output:
30
60
8. Scope of Variables:
A variable is only available from inside the region it is created. This is called scope.
There are 3 basic scopes of variables in Python
1. Global Variables
2. Local Variables
3. Nonlocal Variables
1. Global Variables:
In Python, a variable declared outside of the function or in global scope is known as a global
variable. This means that a global variable can be accessed inside or outside of the function.
Example : Create a Global Variable
x = "global”
def foo():
print("x inside:", x) //inside
foo()
print("x outside:", x) //outside
In the above code, we created x as a global variable and defined a foo() to print the global
What if you want to change the value of x inside a function?
x = "global"
def foo():
x=x*2
print(x)
foo()
Output:
UnboundLocalError: local variable 'x' referenced before assignment

The output shows an error because Python treats x as a local variable and x is also not defined
inside foo().
2. Local Variables:
A variable declared inside the function's body or in the local scope is known as a local variable.

Example : Accessing local variable outside the scope


def foo():
y = "local"
foo()
print(y)

Output:
NameError: name 'y' is not defined

The output shows an error because we are trying to access a local variable y in a global scope
whereas the local variable only works inside foo() or local scope.
Example: Create a Local Variable
Normally, we declare a variable inside the function to create a local variable.
def foo():
y = "local"
print(y)
foo()
Output:
local
Global and local variables
Let's take a look at the earlier problem where x was a global variable and we wanted to
modify x inside foo().
Here, we will show how to use global variables and local variables in the same code.
Example : Using Global and Local variables in the same code
x = "global "
def foo():
global x Output:

y = "local" global global

x=x*2 local

print(x)
In the above code, we declare x as a global and y as a local variable in the
print(y)
foo(). Then, we use multiplication operator * to modify the global variable x
foo()
and we print both x and y. After calling the foo(), the value of x becomes
global global because we used the x * 2 to print two times global. After that,
we print the value of local variable y i.e local.
Example : Global variable and Local variable with same name
x=5
Output:
def foo():
local x: 10
x = 10
global x: 5
print("local x:", x)
foo()
print("global x:", x)

In the above code, we used the same name x for both global variable and local variable. We get
a different result when we print the same variable because the variable is declared in both scopes,
i.e. the local scope inside foo() and global scope outside foo().

When we print the variable inside foo() it outputs local x: 10. This is called the local scope of
the variable.

Similarly, when we print the variable outside the foo(), it outputs global x: 5. This is called the
global scope of the variable.
3. Nonlocal Variables:
 Nonlocal variables are used in nested functions whose local scope is not defined. This
means that the variable can be neither in the local nor the global scope.
 We use nonlocal keywords to create nonlocal variables.
Example : Create a nonlocal variable
def outer():
x = "local"
Output:
def inner():
inner: nonlocal
nonlocal x
outer: nonlocal
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
outer()
In the above code, there is a nested inner() function. We use nonlocal keywords to create a
nonlocal variable. The inner() function is defined in the scope of another function outer().
9. Python Anonymous/Lambda Function:
In Python, an anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword in Python,
anonymous functions are defined using the lambda keyword.
Hence, anonymous functions are also called lambda functions.

Syntax of Lambda Function in python


lambda arguments: expression

Lambda functions can have any number of arguments but only one expression.
The expression is evaluated and returned. Lambda functions can be used wherever function
objects are required.
Here is an example of lambda function that doubles the input value.
# Program to show the use of lambda functions
double = lambda x: x * 2
print(double(5))
In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x *
2 is the expression that gets evaluated and returned.
This function has no name. It returns a function object which is assigned to the identifier
double.

double = lambda x: x * 2

If we use a normal function. The statement is nearly the same as:


def double(x):
return x * 2
10. Strings Indexing and Splitting:
For example in string, we can access individual character using indexing and a range of
characters using slicing. Index starts from 0 and ends with length -1, and this index must be
str=“HELLO”
an integer.
H E L L O
Forward indexing 0 1 2 3 4

In indexing, for accessing the individual character we can use slice operator [ ], inside that
specify index number.
str[0]=‘H’
str[3]=‘L’
str[1]=‘E’
str[4]=‘O’
str[2]=‘L’

if we try to access a character out of index range then interpreter will raise an IndexError.
>>> str[5]
Traceback (most recent call last): The index must be an integer if we try to
File "<pyshell#1>", line 1, in <module> access the data with non-integer indexes
str[5]
IndexError: string index out of range values then interpreter raises an TypeError.
Slicing means taking elements from one given index to another given index.
In slicing, by using the slice operator [ ] we can access the range of characters of the string.
Inside square bracket[ ] we can use the : operator to access the substring.(positive indexing).
We pass slice instead of index like this: [start:end].
If we don't pass start its considered 0
If we don't pass end its considered length of string.

str=“HELLO”
H E L L O

Forward indexing 0 1 2 3 4
Python allows negative indexing for its sequence. The index of -1 refers to the last
item, -2 refers to last 2nd item. This is called backward indexing

str=‘hello’
h e l l o
-5 -4 -3 -2 -1
>>> str[-1]
Backward indexing
'o'
>>> str[-3]
'l‘
>>> str[:-3]
'he'
>>> str[-3:]
'llo‘
>>> str[-3:-2]
'l‘
>>> str[-2:-2] # return empty strings.
‘'
>>> str[2:2] # return empty strings.
‘'
String splitting:
split()
split() method breaks up a string at the specified separator and returns a list of strings.
syntax of split() is:
str.split(separator)
separator (optional)- It is a delimiter. The string splits at the specified separator. If the separator is not
specified, any whitespace (space) string is a separator.
Ex:
text='hello python programming'
# splits at space
print(text.split())
grocery = 'Milk, Chicken, Bread' Output:
# splits at ','
[‘hello', ‘python',
print(grocery.split(', '))
‘programming']
grocery1 = 'Milk, Chicken: Bread:coffee'
['Milk', 'Chicken', 'Bread']
# Splitting at ':'
print(grocery1.split(':'))
['Milk, Chicken, Bread']
11.String Operators:
In python, String operators represent the different types of operations that can be employed on
the program’s string type of variables. Python allows several string operators that can be applied
on the python string are as below:
1. Assignment operator: “=.”
2. Concatenate operator: “+”
3. String repetition operator: “*”
4. String slicing operator: “[]”
5. String comparison operator: “==” & “!=”
6. Membership operator: “in” & “not in”
7. Escape sequence operator: “\”
8. String formatting operator: “%” & “{}”
1. Assignment Operator “=”
Python string can be assigned to any variable with an assignment operator “= “.
Python string can be defined with either single quotes [‘ ’], double quotes[“ ”] or triple
quotes[‘’’ ‘’’]. var_name = “string” assigns “string” to variable var_name.

Code:
string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
print(string1)
print(string2)
print(string3)
Output:
2. Concatenate Operator “+”
Two strings can be concatenated or join using “+” operator in python, as explained in the
below example code:
Code:
string1 = "hello"
string2 = "world "
string_combined = string1+string2
print(string_combined)

Output:
3.String Repetition Operator “*”
The same string can be repeated in python by n times using string*n as explained in the
below example.
Code:
string1 = "helloworld "
print(string1*2)
print(string1*3)
print(string1*4)
print(string1*5)
Output:
4. String slicing operator “[]”
Characters from a specific index of the string can be accessed with the string[index]
operator. The index is interpreted as a positive index starting from 0 from the left side
and a negative index starting from -1 from the right side.

String H E L L O W O R L D

Positive 0 1 2 3 4 5 6 7 8 9
index

Negativ -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
e index
•string[a]: Returns a character from a positive index a of the string from the left side as
displayed in the index graph above.
•string[-a]: Returns a character from a negative index a of the string from the right side as
displayed in the index graph above.
•string[a:b]: Returns characters from positive index a to positive index b of the as displayed in
index graph above.
•string[a:-b]: Returns characters from positive index a to the negative index b of the string as
displayed in the index graph above.
•string[a:]: Returns characters from positive index a to the end of the string.
•string[:b] Returns characters from the start of the string to the positive index b.
•string[-a:]: Returns characters from negative index a to the end of the string.
•string[:-b]: Returns characters from the start of the string to the negative index b.
•string[::-1]: Returns a string with reverse order.
Code:
string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])
Output:
5. String Comparison Operator “==” & “!=”
The string comparison operator in python is used to compare two strings.
•“==” operator returns Boolean True if two strings are the same and return Boolean False if two strings
are not the same.
•“!=” operator returns Boolean True if two strings are not the same and return Boolean False if two
strings are the same.
These operators are mainly used along with if condition to compare two strings where the decision is to
be taken based on string comparison.

Code:
string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4) Output:
print(string2==string3)
print(string1!=string4)
print(string2!=string3)
6. Membership Operator “in” & “not in”:
Membership operator is used to searching whether the specific character is part/member of a
given input python string.
“a” in the string: Returns boolean True if “a” is in the string and returns False if “a” is not in
the string.
“a” not in the string: Returns boolean True if “a” is not in the string and returns False if “a”
is in the string.
A membership operator is also useful to find whether a specific substring is part of a given
string.
Code:
string1 = "helloworld"
print("w" in string1)
print("W" in string1) Output:
print("t" in string1)
print("t" not in string1)
print("hello" in string1)
7. Escape Sequence Operator “\.”
To insert a non-allowed character in the given input string, an escape character is used.
 An escape character is a “\” or “backslash” operator followed by a non-allowed
character.
An example of a non-allowed character in python string is inserting double quotes in the
string surrounded by double-quotes.

1. Example of non-allowed double quotes in python string:


Code:
string = "Hello world I am from "India""
print(string)

Output:
2. Example of non-allowed double quotes with escape sequence operator:
Code:
string = "Hello world I am from \"India\""
print(string)
Output:
8. String Formatting Operator “%.”
String formatting operator is used to format a string as per requirement. To insert another
type of variable along with string, the “%” operator is used along with python string.

“%” is prefixed to another character indicating the type of value we want to insert along
with the python string.

Please refer to the below table for some of the commonly used different string formatting
specifiers:
Operator Description

%d Signed decimal integer

%u unsigned decimal integer

%c Character

%s String

%f Floating-point real number


Code:
name = "india"
age = 19
marks = 20.56
string1 = 'Hey %s' % (name)
print(string1)
string2 = 'my age is %d' % (age)
print(string2)
string3= 'Hey %s, my age is %d' % (name, age)
print(string3)
string3= 'Hey %s, my subject mark is %f' % (name, marks)
print(string3)
Output:
12. What is a file?
File is a named location on disk to store related information. It is used to permanently
store data in a non-volatile memory (e.g. hard disk).

Since, random access memory (RAM) is volatile which loses its data when computer is
turned off, we use files for future use of the data.

If you are working in a large software application where they process a large number of
data, then we cannot expect those data to be stored in a variable as the variables are
volatile in nature.

As files are non-volatile in nature, the data will be stored permanently in a secondary
device like Hard Disk
How Python Handle Files?
If you are working in a large software application where they process a large number of
data, then we cannot expect those data to be stored in a variable as the variables are
volatile in nature.
As files are non-volatile in nature, the data will be stored permanently in a secondary
device like Hard Disk.

Types Of File in Python


There are two types of files in Python.
They are:
1.Binary file
2.Text file
1. Binary files in Python
Most of the files that we see in our computer system are called binary files.
Example:
Document files: .pdf, .doc, .xls etc.
Image files: .png, .jpg, .gif, .bmp etc.
Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac etc.
Database files: .mdb, .accde, .frm, .sqlite etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc.
All binary files follow a specific format. We can open some binary files in the normal text
editor but we can’t read the content present inside the file. That’s because all the binary
files will be encoded in the binary format, which can be understood only by a computer or
machine. For handling such binary files we need a specific type of software to open it.
For Example, You need Microsoft word software to open .doc binary files. Likewise, you
need a pdf reader software to open .pdf binary files.
2. Text files in Python
Text files don’t have any specific encoding and it can be opened in normal text editor
itself.
Example:
Web standards: html, XML, CSS, JSON etc.
Source code: c, app, js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Configuration: ini, cfg, reg etc.
.
13. Python File Handling Operations
Most importantly there are 4 types of operations that can be handled by Python on files:
1. Open
2. Read
3. Write
4. Close
Other operations include:
1. Rename
2. Delete
1. How to open a file?
Python provides the open() function which accepts two arguments, file name and
access mode in which the file is accessed.
 The function returns a file object which can be used to perform various operations like
reading, writing, etc.
File object:
File objects contain methods and attributes that can be used to collect information
about the file you opened. They can also be used to manipulate said file.
To get a file object we use Python’s built-in open function
Syntax:
file_object = open(“filename”, “mode”)
where file_object is the variable to add the file object.
File objects contain methods and attributes that can be used to collect
information about the file you opened. They can also be used to manipulate
said file.
mode – tells the interpreter and developer which way the file will be used.
Access Modes for File Objects

r: Opens the file in read-only mode. Starts reading from the beginning of the file and is
the default mode for the open() function.

w: Opens in write-only mode. The pointer is placed at the beginning of the file and this
will overwrite any existing file with the same name. It will create a new file if one with the
same name doesn't exist.

a: Opens a file for appending new information to it. The pointer is placed at the end of
the file. A new file is created if one with the same name doesn't exist.

r+: Opens a file for reading and writing, placing the pointer at the beginning of the file.

w+: Opens a file for writing and reading.

a+: Opens a file for both appending and reading.


rb: Opens the file as read-only in binary format and starts reading from the beginning of the
file. While binary format can be used for different purposes, it is usually used when dealing with
things like images, videos, etc.

wb: Opens a write-only file in binary mode.

ab: Opens a file for appending in binary mode.

rb+: Opens a file for reading and writing in binary mode.

wb+: Opens a file for writing and reading in binary mode.

ab+: Opens a file for both appending and reading in binary mode
Ex:

#Create a text file


>>> with open("fdp1.py","w") as f:
f.write("this is 1st program")
>>> f=open(“fdp.txt","w") or
f.close()
>>> f
<_io.TextIOWrapper name='demo.txt' mode='w' encoding='cp1252'>

#to know the current path


>>> import os
>>> os.path

<module 'ntpath' from C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\ntpath.py '>


2. How to write in to file:
In order to write into a file in Python, we need to open it in write w, or append a .

Writing a string or sequence of bytes (for binary files) is done using


the write() method. This method returns the number of characters written to the file.

Ex:
>>> f=open(“fdp.txt","w")
>>> f.write("this is first line\n")
18
>>> f.close()
Then open fdp.txt file in your path.

We need to be careful with the w mode, as it will overwrite into the file if it already
exists. Due to this, all the previous data are erased.
How to append new data in to existing file:
>>> f=open(“fdp.txt","a")
>>> f.write(" \n This is file concepts in python\n")
35
>>> f.write(" \nThis is append method")
23
>>> f.close()

NOTE: open fdp.txt file for output

Shall we write multiple lines in file with write() function?


Answer is NO
How to write multiple lines in file:
writelines():
The method writelines() writes a sequence of strings to the file.
 The sequence can be any iterable object producing strings, typically a list of
strings.
There is no return value.
Syntax:
fileObject.writelines( sequence )
# Where sequence − This is the Sequence of the strings.
Ex:
>>> f=open(“fdp.txt","w")
>>> a=f.writelines(["this is writelines function\n","previous function is write
function"])
>>>f.close()

Note: open fdp txt file in your path and see the text
3.Reading a Text File in Python:
If you need to extract a string that contains all characters in the file.
Syntax:
fileobject.read()
Ex;
>>> f=open(“fdp.txt","r")
>>>a= f.read()
>>>print(a) // to print all characters in the file

Ex:
this is first line
This is file concepts in python
This is append method
this is writelines function
previous function is write function
For suppose , if we want to get a character ,then use slicing concept
>>> f=open("fdp.py","r")
>>> a=f.read()
>>> print(a[2])
i
>>> print(a[0:])
this is first line
This is file concepts in python
This is append method
this is writelines function
previous function is write function
For suppose, I want to read a file is to call a certain number of characters.
>>> f=open(“fdp.txt","r")
>>> a=f.read(22)
>>>print(a)
Ex:
this is first line
Thi

How to read multiple lines in file:


If you want to read a first line from file, then you use the readline() function.

Ex: #Displaying first line from file


>>> f=open(“fdp.txt","r") >>> print(open(“fdp.txt","r").readlin
>>> a=f.readline() or this is first line
>>>print(a)
this is first line
For suppose, in first line I want 2nd character then use a[1]
>>> f=open("fdp.py","r")
>>> a=f.readline()
>>> print(a[1])
h

We can also specify bytes in readline(),which returns specified bytes from first line.

Return only the five first bytes from the first line:
>>>f = open(“fdp.txt", "r")
>>>print(f.readline(5))
this
readlines():
 If you want to read a data line by line from file, then you use the readlines() function

Ex: #Displaying first line from file #Displaying second line from file
>>> f=open(“fdp.txt","r")
>>> f=open(“fdp.txt","r") >>> a=f.readlines()
>>> a=f.readlines() >>>print(a[1])
>>> print(a[0]) This is file concepts in python
this is first line

For suppose, If we want last line then use a[-1]

>>> f=open(“fdp.txt","r")
>>> a=f.readlines()
>>>print(a[-1])
previous function is write function
4. Python Close File
In order to close a file, we must first open the file. In python, we have an in-built method
called close() to close the file which is opened.
Whenever you open a file, it is important to close it, especially, with write method.
Because if we don’t call the close function after the write method then whatever data we
have written to a file will not be saved into the file.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World”)
my_file.close()
5. Python Rename():
Python provides us with an “os” module which has some in-built methods that
would help us in performing the file operations such as renaming and deleting the
file.
In order to use this module, first of all, we need to import the “os” module in our
program and then call the related methods.
rename() method:
This rename() method accepts two arguments i.e. the current file name and the new
file name.
Syntax:
os.rename(current_file_name, new_file_name)
Ex:
>>> import os
>>> os.rename("fdp1.txt","fdp2.txt")
6. Python remove() method:
We use the remove() method to delete the file by supplying the file name or the file
location that you want to delete.
Syntax:
os.remove(file_name)

Example :
import os
os.remove("fdp2.txt")
14. Looping through the File:
We can iterate through the file handle, no need to call readlines().on large files, you don't
have to read all the lines (that's what readlines() does) at once.
In a with-statement, use open(file, mode) with mode as "r" to open file for reading. Inside
the with-statement, use a for-loop to iterate through the lines. Then, call str.strip() to strip
the end-line break from each line.
SAMPLE.TXT
This is
an existing file.
-----------------------------------
with open("sample.txt", "r") as a_file:
for line in a_file:
stripped_line = line.strip()
print(stripped_line)
OUTPUT
This is
15. File Pointer Position:
Python file method tell() returns the current position of the file read/write pointer within the
file.
1.tell() in Python
tell() tells us the current position of the cursor
Syntax
Following is the syntax for tell() method −
fileObject.tell()
Return Value
This method returns the current position of the file read/write pointer within the file.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seek(20)
20
>>> print(f.readline())
This is file concepts in python\n'
16. Modifying File Pointer Position:
The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the reference
position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end of
the file would be taken as the reference position.
1.seek() in python:
The seek() method sets the current file position in a file stream.
Syntax
file.seek(offset)
Where offset is a number representing the position to set the current file stream position.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seek(20)
>>> print(f.readline()) #output: ‘This is file concepts in python\n‘
17. File Built-in Methods
1. close()
2. fileno()
3. read()
4. readable()
5. readline( )
6. readlines()
7. seek()
8. seekable()
9. tell()
10.truncate()
11.writable()
12.write()
13.writelines()
14.detach
1. close() in Python
With close(), we close a file to free up the resources held by it.
Ex:
>>> f=open(“fdp.txt","w")
>>> f.write("this is first line\n")
18
>>> f.close()

2. fileno() in Python
t is used to get the file number i.e. the file descriptor as an integer of the stream.
It may return an error if an operating system does not use a file descriptor of the file is closed.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.fileno()
4
3. read() in Python
The read() method returns the specified number of bytes from the file.
Syntax:
file.read(size)
Where size is the number of bytes to be read from the file.
Ex:
>>> f=open("abc.txt","r")
>>> a=f.read()
>>> print(a)
4. readable() in Python
This returns True if the object is readable
Ex:
>>> f=open("abc.txt",”r")
>>> f.readable()
True
>>> f=open("abc.txt","w")
>>> f.readable()
False
>>> f=open("abc.txt","a")
>>> f.readable()
False
5. readline( ) in Python:
The readline() method returns first line from the file.
Syntax
file.readline(size)
Ex:
>>> f=open("abc.txt","r")
>>> a=f.readline()
>>>print(a)
welcome to python programming

You can also specified how many bytes from the line to return, by using the size
parameter.

Return only the five first bytes from the first line:
>>>f = open("demofile.txt", "r")
>>>print(f.readline(5))
6. readlines() in Python:
readlines() method returns a list containing each line in the file as a list item.
Ex:
>>> f=open("demo.txt","r")
>>> a=f.readlines()
>>> print(a)
['hi...hello...python‘,’welcome to python world']

7. seek() in python:
The seek() method sets the current file position in a file stream.
Syntax
file.seek(offset)
Where offset is a number representing the position to set the current file stream position.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seek(20)
8. seekable() in Python
This returns whether file allows us to change the file position
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seekable()
True

9. tell() in Python
tell() tells us the current position of the cursor.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seek(20)
20
>>> print(f.readline())
This is file concepts in python\n'
>>> print(f.tell())
10. truncate():
This method truncates the file's size. If the optional size argument is present, the file is
truncated to (at most) that size.
The size defaults to the current position
This method would not work in case file is opened in read-only mode.
Syntax:
fileObject.truncate( [ size ])
Example:
>>> f=open(“fdp.txt","w")
>>> #fdp.txt size is 139bytes
>>> f.truncate()
0
>>> #fdp.txt size is 0 bytes
11. writable() in Python
This returns True if the stream can be written to.
Ex:
>>> f=open(“fdp.txt","w")
>>> f.writable()
True
>>> f=open(“fdp.txt","r")
>>> f.writable()
False
12. write(s) in Python
This method takes string ‘s’, and writes it to the file. Then, it returns the number of
characters written.
Ex:
>>> f=open(“fdp.txt","w")
>>> f.write("truncate function")
17
13. writelines():
The method writelines() writes a sequence of strings to the file.
 The sequence can be any iterable object producing strings, typically a list of strings.
There is no return value.
Syntax:
fileObject.writelines( sequence)
# Where sequence − This is the Sequence of the strings.
Ex:
>>> f=open(“fdp.txt","w")
>>> a=f.writelines(["this is writelines function\n","previous function is write function"])
>>>f.close()
Note: open new.txt file in your path and see the text
14. detach( ):
This detaches the underlying binary buffer from TextIOBase and returns raw stream
from buffer.
syntax:
f.detach()
Ex:
>>> f=open("ab.txt","r")
>>> f.detach()
<_io.BufferedReader name='ab.txt'>
>>> f.read()
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
f.read()
ValueError: underlying buffer has been detached
18. Python file Built-in attributes:

Ex:
>>> f=open("new.txt","w")
>>> print("Name of the File:",f.name)
Name of the File: new.txt
>>> print("Mode of the File:",f.mode)
Mode of the File: w
>>> print("closed?:",f.closed)
closed?: False
>>> f.close()
>>> print("closed?:",f.closed)
closed?: True
>>> print("Encoding of the File:",f.encoding)
Encoding of the File: cp1252

Encoding in Files
File encoding represents converting characters into a specific format which only a
machine can understand.
Different machines have different encoding format as shown below.
Microsoft Windows OS uses ‘cp1252’ encoding format by default.
Linux or Unix OS uses ‘utf-8’ encoding format by default.
Apple’s MAC OS uses ‘utf-8’ or ‘utf-16’ encoding format by default.
19. Error and Exceptions
What Are Exceptions?
 In the context of software, errors are either syntactical or logical in nature.

 Syntax errors indicate errors with the construct of the software and cannot be executed

by the interpreter or compiled correctly.

 These errors must be repaired before execution can occur.

 Once programs are semantically correct, the only errors that remain are logical.

 Logical errors/ Run time errors can either be caused by lack of or invalid input, or by

the inability of the logic to generate, calculate, or otherwise produce the desired results

based on the input.

 Run time errors are also called Exceptions

 These errors are sometimes known as domain and range failures.


20. Common Exceptions:
An exception can be defined as an abnormal condition in a program resulting in the
disruption in the flow of the program.

Whenever an exception occurs, the program halts the execution, and thus the further code
is not executed. Therefore, an exception is the error which python script is unable to tackle
with.

Python provides us with the way to handle the Exception so that the other part of the
code can be executed without any disruption. However, if we do not handle the exception,
the interpreter doesn't execute all the code that exists after the that..

There are two types of exception:


1.System defined exceptions
2.User-defined exceptions
1. System defined exceptions:
A list of System defined exceptions that can be thrown from a normal python program is
given below.
ZeroDivisionError: Occurs when a number is divided by zero.
NameError: It occurs when a name is not found. It may be local or global.
IndentationError: If incorrect indentation is given.
IOError: It occurs when Input Output operation fails.
EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.
1. ZeroDivisionError:
Occurs when a number is divided by zero
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value0
>>> c=a/b

Traceback (most recent call last):


File "<pyshell#3>", line 1, in <module>
c=a/b
ZeroDivisionError: division by zero
2.Type error:
Ex:
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value5
>>> c=a/'b'
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
c=a/'b'
TypeError: unsupported operand type(s) for /: 'int' and 'str‘
3. NameError:
Ex:
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value6
>>> c=a/d
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
c=a/d
NameError: name 'd' is not defined
4. SyntaxError: Python interpreter syntax error
>>> for
File "<string>", line 1
for
^
SyntaxError: invalid syntax

SyntaxError exceptions are the only ones that do not occur at run-time.
 They indicate an improperly constructed piece of Python code which cannot execute
until corrected.
 These errors are generated at compile-time, when the interpreter loads and attempts
to convert your script to Python bytecode
5. IndexError: request for an out-of-range index for sequence
>>> aList = []
>>> aList[0]
Traceback (innermost last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
IndexError is raised when attempting to access an index that is outside the valid range of a
sequence.
6. KeyError: request for a non-existent dictionary key
>>> aDict = {'host': 'earth', 'port': 80}
>>> print aDict['server']
Traceback (innermost last):
File "<stdin>", line 1, in ?
KeyError: server
Mapping types such as dictionaries depend on keys to access data values. Such values are
not retrieved if an incorrect/nonexistent key is requested.
7.IOError: input/output error
>>> f = open("blah")
Traceback (innermost last):
File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'blah‘

Attempting to open a nonexistent disk file is one example of an operating system


input/output (I/O) error. Any type of I/O error raises an IOError exception
21. Except Statement with no Exception:
Exception handling in python:
1.ZeroDivisionError: Traceback (most recent call last):
Occurs when a number is divided by zero. File "<pyshell#3>", line 1, in
>>> a=eval(input("enter a value")) <module>
enter a value4 c=a/b
>>> b=eval(input("enter b value")) ZeroDivisionError: division by
enter b value0 zero
>>> c=a/b

If the python program contains suspicious code that may throw the exception, we must place
that code in the try block.
The try block must be followed with the except statement which contains a block of code that
will be executed if there is some exception in the try block.
When an error occurs with in try block .python looks for matching except block to handle it ,if
Ex:
a=int(input("enter a value"))
b=int(input("enter b value"))
try:
c=a/b
print("the result is",c)
except:
print("error occured“)

C:\Users\ajee\Desktop\py>exception.py
enter a value4
enter b value0
error occured

C:\Users\ajee\Desktop\py>exception.py
enter a value4
enter b value2
The result is 2
2.Type error:
Ex:
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value5
>>> c=a/'b'
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
c=a/'b'
TypeError: unsupported operand type(s) for /: 'int' and 'str‘

a=int(input("enter a value"))
b=int(input("enter b value"))
try:
c=a/'b'
print("the result is",c)
except:
print("error occured")

C:\Users\ajee\Desktop\py>typeerror.py
enter a value3
enter b value 4
error occured
3. NameError:
Ex:
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value6
>>> c=a/d
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
c=a/d
NameError: name 'd' is not defined

a=int(input("enter a value"))
b=int(input("enter b value"))
try:
c=a/d
print("the result is",c)
except:
print("error occured")
C:\Users\ajee\Desktop\py>nameerror.py
enter a value2
enter b value3
error occured
22. Declaring Multiple Exceptions:
except Statement with Multiple Exceptions:
The python allows us to declare the multiple exceptions with the except clause.
Declaring multiple exceptions is useful in the cases where a try block throws multiple
exceptions.
Ex:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/b;
print("a/b = %d"%c)
except ZeroDivisionError:
print("please enter non-zero for denimoniator")
except NameError:
print("please use defined names only")
except TypeError:
print("please use proper types only")

C:\Users\ajee\Desktop\py>except.py
Enter a:4
Enter b:0
please enter non-zero for denimoniator
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/'b';
print("a/b = %d"%c)
except ZeroDivisionError:
print("please enter non-zero for denimoniator")
except NameError:
print("please use defined names only")
except TypeError:
print("please use proper types only")

C:\Users\ajee\Desktop\py>except.py
Enter a:4
Enter b:2
please use proper types only
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/d;
print("a/b = %d"%c)
except ZeroDivisionError:
print("please enter non-zero for denimoniator")
except NameError:
print("please use defined names only")
except TypeError:
print("please use proper types only")

C:\Users\ajee\Desktop\py>except.py
Enter a:4
Enter b:6
please use defined names only
some of the exception errors
except IOError:
print('An error occurred trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except ImportError:
print "NO module found"
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the operation.')
except:
print('An error occurred.')
23. Declaring multiple exceptions (or )except Statement with
Multiple Exceptions

The python allows us to declare the multiple exceptions with the except clause.
 Declaring multiple exceptions is useful in the cases where a try block throws multiple
exceptions.
Syntax
try:
#block of code

except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)


#block of code

else:
#block of code
24. Handling All Exceptions:

If you really want to handle all errors, you can still do that too, but use BaseException
try:
except BaseException, e: - BaseException
# handle all errors |- KeyboardInterrupt
or |- SystemExit
try: |- Exception
except Exception, e: |- (all other current built-in exceptions)
# handle real errors
Python exception hierarchy or standard exceptions:
25. else block:
We can also use the else statement with the try-except statement in which, we can place the
code which will be executed in the scenario if no exception occurs in the try block.
Ex:
a = int(input("Enter a:"))
C:\Users\ajee\Desktop\py>else.py
b = int(input("Enter b:"))
Enter a:4
try:
Enter b:0
c = a/b
can't divide by zero
print("a/b = %d"%c)
except:
C:\Users\ajee\Desktop\py>else.py
print("can't divide by zero")
Enter a:4
else:
Enter b:2
print("Hi I am else block")
a/b = 2
Hi I am else block
26. Finally block

The finally block will be executed regardless if the try block raises an error or
not.

a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/b
print("a/b = %d"%c)
except :
print("please enter non-zero for denimoniator")
else:
print("Hi I am else block")
finally:
print("Thank you")
C:\Users\ajee\Desktop\py>except.py
C:\Users\ajee\Desktop\py>except.py Enter a:4
Enter a:4 Enter b:0
Enter b:3 please enter non-zero for denimoniator
a/b = 1 Thank you
Hi I am else block
Thank you
27. Assert statement in python:

Python has built-in assert statement to use assertion condition in the program.
 assert statement has a condition or expression which is supposed to be always true.
If the condition is false assert halts the program and gives an assertionError.
 It is used for debugging

Syntax:
assert <condition>,<error message>
Here error message is optional
Ex:
x = "hello”
assert x == "hello“
print(x)
#if condition returns False, AssertionError is raised
assert x == "goodbye", "x should be 'hello‘“
o/p:
hello
Traceback (most recent call last):

File "main.py", line 17, in <module>


assert x == "goodbye", "x should be 'hello‘”
28. User defined exception:
User can also define exceptions to indicate something is going wrong in your
program ,those are called customized exception or programmatic exception.
The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.

ex: Raise an error and stop the program if x is lower than 0:


x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero“)
o/p:
Traceback (most recent call last):
File "demo_ref_keyword_raise.py", line 4, in <module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero

Ex: Raise a TypeError if x is not an integer:

x = "hello”
if not type(x) is int:
raise TypeError("Only integers are allowed")
Exceptions and the sys Module:
An alternative way of obtaining exception information is by accessing the exc_info()
function in the sys module. This function provides a 3-tuple of information.
1. exc_type: exception class object
2. exc_value: (this) exception class instance object
3. exc_traceback: traceback object
Ex:
>>> try:
float('abc123')
except:
import sys
exc_tuple = sys.exc_info()
>>> print(exc_tuple)
( <class exceptions.ValueError at f9838>, <exceptions.ValueError instance at 122fa8>,
<traceback object at 10de18> )

You might also like