2. Lists :
A list is an ordered set of values, where each value is identified by an
index.
The values that make up a list are called its elements .
Lists are similar to strings, which are ordered sets of characters, except
that the elements of a list can have any type.
Lists and strings—and other things that behave like ordered sets—are
called sequences .
The list is the most versatile datatype available in Python, which can be
written as a list of comma-separated values (items) between square
brackets.
Important thing about a list is that the items in a list need not be of the
same type.
There are several ways to create a new list; the simplest is to enclose the elements
in square brackets ([ and ]):
[10, 20, 30, 40] ["spam", "bungee", "swallow"]
3. A list within another list is said to be nested .
Finally, there is a special list that contains no elements.
It is called the empty list, and is denoted []. Like numeric 0 values and the empty
string, the empty list is false in a boolean expression:
-------------------------------------------------------------------------------------------------
Values and Accessing Elements:
The values stored in a list can be accessed using the slice operator ([ ] and
[:]) with indexes starting at 0 in the beginning of the list and working their
way to end -1.
The plus (+) sign is the list concatenation operator, and the asterisk (*) is
the repetition operator.
4. #!/usr/bin/python3
list = [ 'abcd', 786 , 2.23, 'john',
70.2 ] tinylist = [123, 'john']
print (list)
print (list[0]) print (list[1:3])
# Prints complete list
# Prints first element of the list
# Prints elements starting from 2nd
till 3rd print (list[2:])
# Prints elements starting
from 3rd element print (tinylist * 2) # Prints list two
times
print (list + tinylist) # Prints concatenated lists
5. Lists are mutable :
Unlike strings lists are mutable , which means we can change their elements.
Using the bracket operator on the left side of an assignment, we can update one of the
elements:
>>> fruit = ["banana", "apple", "quince"]
>>> fruit[0] = "pear"
>>> fruit[-1] = "orange"
>>> print fruit
[’pear’, ’apple’, ’orange’]
Explanation:
The bracket operator applied to a list can appear anywhere in an expression. When it
appears on the left side of an assignment, it changes one of the elements in the list, so
the first element of fruit has been changed from "banana" to "pear", and the last from
"quince" to "orange".
An assignment to an element of a list is called item assignment.
6. Item assignment does not work for strings:
>>> my_string = "TEST"
>>> my_string[2] = "X"
Traceback (most recent call last): File "<stdin>", line 1, in
<module>
TypeError: ’str’ object does not support item assignment
---------------------------------------------------------------------------------------------------------------------------------
but it does for lists:
>>> my_list = ["T", "E", "S", "T"]
>>> my_list[2] = "X"
>>> my_list
[’T’, ’E’, ’X’, ’T’]
7. With the slice operator we can update several elements at once:
>>> a_list = ["a", "b", "c", "d", "e", "f"]
>>> a_list[1:3] = ["x", "y"]
>>> print a_list
[’a’, ’x’, ’y’, ’d’, ’e’, ’f’]
We can also remove elements from a list by assigning the empty list to them:
>>> a_list = ["a", "b", "c", "d", "e", "f"]
>>> a_list[1:3] = []
>>>
print a_list [’a’,
’d’,
’e’,
’f’]
8. And we can add elements to a list by squeezing them into an empty slice at the
desired location:
>>> a_list = ["a", "d", "f"]
>>> a_list[1:1] = ["b", "c"]
>>> print a_list
[’a’, ’b’, ’c’, ’d’, ’f’]
>>> a_list[4:4] = ["e"]
>>> print a_list
[’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
---------------------------------------------------------------------------------------------------
9. Deleting elements from List :
To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting.
You can use the remove() method if you do not know exactly which items to delete.
#!/usr/bin/python3
list = ['physics', 'chemistry', 1997, 2000] print (list)
del list[2]
print ("After deleting value at index 2 : ", list)
When the above code is executed, it produces the following result-
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 : ['physics', 'chemistry', 2000]
Note: remove() method is discussed in subsequent section.
10. Built-in List Operators, Concatenation, Repetition, In Operator :
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
11. Built-in List functions and methods :
Python includes the following list functions :
12. Listlen()Method
Description
The len() method returns the number of elements in the list.
Syntax
Following is the syntax for len() method-
len(list)
Parameters
list - This is a list for which, number of elements are to be counted.
Return Value
This method returns the number of elements in the list.
Example
The following example
list1 = ['physics', 'chemistry', 'maths']
print (len(list1))
list2=list(range(5)) #creates list of numbers between 0-4 print (len(list2)) shows the usage of len()
method.
13. List max() Method :
Description
The max() method returns the elements from the list with maximum value.
Syntax
Following is the syntax for max() method-
max(list)
Parameters
list - This is a list from which max valued element are to be returned.
Return Value
This method returns t
Example
The following example shows the usage of max() method.
list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))
14. List min() Method :
Description
The method min() returns the elements from the list with minimum value.
Syntax
Following is the syntax for min() method-
min(list)
Parameters
list - This is a list from which min valued element is to be returned.
Return Value
This method returns the elements from the list with minimum value.
list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]
print ("min value element : ", min(list1))
print ("min value element : ", min(list2))
15. List list() Method :
Description
The list()method takes sequence types and converts them to lists. This is used to convert a
given tuple into list.
Note: Tuple are very similar to lists with only difference that element values of a tuple can
not be changed and tuple elements are put between parentheses instead of square bracket.
This function also converts characters in a string into a list.
Syntax
Following is the syntax for list() method-
list( seq )
Parameters
seq - This is a tuple or string to be converted into list.
Return Value : This method returns the list.
aTuple = (123, 'C++', 'Java', 'Python') list1 = list(aTuple)
print ("List elements : ", list1)
str="Hello World" list2=list(str) print ("List elements : ", list2)
17. List append() Method :
Description
The append() method appends a passed obj into the existing list.
Syntax
Following is the syntax for append() method-
list.append(obj)
Parameters
obj - This is the object to be appended in the list.
Return Value
This method does not return any value but updates existing list.
Example
list1 = ['C++', 'Java', 'Python']
list1.append('C#')
print ("updated list : ", list1)
NOTE: append method used to add element in list at last position
18. List count()Method
Description
The count() method returns count of how many times obj occurs in list.
Syntax
Following is the syntax for count() method-
list.count(obj)
Parameters
obj - This is the object to be counted in the list.
Return Value
This method returns count of how many times obj occurs in list.
aList = [123, 'xyz', 'zara', 'abc', 123]; print ("Count for 123 : ", aList.count(123))
print ("Count for zara : ", aList.count('zara'))
O/P
Count for 123 : 2
Count for zara : 1
19. Listextend()Method
Description
The extend() method appends the contents of seq to list.
Syntax
list.extend(seq)
Parameters
seq - This is the list of elements
Return Value
This method does not return any value but adds the content to an existing list.
list1 = ['physics', 'chemistry', 'maths'] list2=list(range(5)) #creates list of numbers between 0-4
list1.extend('Extended List :', list2)
print (list1)
20. List index() Method
The index() method returns the lowest index in list that obj appears.
Syntax
Following is the syntax for index() method-
list.index(obj)
Parameters
obj - This is the object to be find out.
Return Value
This method returns index of the found object otherwise raises an exception indicating that
the value is not found.
list1 = ['physics', 'chemistry', 'maths']
print ('Index of chemistry', list1.index('chemistry')) print ('Index of C#', list1.index('C#'))
21. List insert() Method
Description
The insert() method inserts object obj into list at offset index.
Syntax
Following is the syntax for insert() method-
list.insert(index, obj)
Parameters
• index - This is the Index where the object obj need to be inserted.
• obj - This is the Object to be inserted into the given list.
Return Value
This method does not return any value but it inserts the given element at the given index.
list1 = ['physics', 'chemistry', 'maths'] list1.insert(1, 'Biology')
print ('Final list : ', list1)
Final list : ['physics', 'Biology', 'chemistry', 'maths']
22. List pop() Method :
Description
The pop() method removes and returns last object or obj from the list.
Syntax
Following is the syntax for pop() method-
list.pop(obj=list[-1])
Parameters
obj - This is an optional parameter, index of the object to be removed from the list.
Return Value
This method returns the removed object from the list.
list1 = ['physics', 'Biology', 'chemistry', 'maths'] list1.pop()
print ("list now : ", list1) list1.pop(1)
print ("list now : ", list1)
o/p
['physics', 'Biology', 'chemistry']
['physics', 'chemistry']
23. Listremove()Method :
Parameters
obj - This is the object to be removed from the list.
Return Value
This method does not return any value but removes the given object from the list.
Example :
list1 = ['physics', 'Biology', 'chemistry', 'maths'] list1.remove('Biology')
print ("list now : ", list1) list1.remove('maths')
print ("list now : ", list1)
list now :
['physics', 'chemistry', 'maths']
['physics', 'chemistry']
24. Listreverse()Method
Description
The reverse() method reverses objects of list in place.
Syntax
Following is the syntax for reverse() method-
list.reverse()
Parameters
NA
Return Value
This method does not return any value but reverse the given object from the list.
list1 = ['physics', 'Biology', 'chemistry', 'maths'] list1.reverse()
print ("list now : ", list1)
o/p
list now :['maths', 'chemistry', 'Biology', 'physics']
25. List sort() Method :
Description
The sort() method sorts objects of list, use compare function if given.
Syntax
Following is the syntax for sort() method-
list.sort([func])
Parameters
NA
Return Value
This method does not return any value but reverses the given object from the list.
list1 = ['physics', 'Biology', 'chemistry', 'maths'] list1.sort()
print ("list now : ", list1)
list now : ['Biology', 'chemistry', 'maths', 'physics']
Note: this method sorts the list as alphabetically , incase of numbers it will
sort according to its value
26. Tuples and Dictionaries :
tuple is a sequence of immutable Python objects.
Tuples are sequences, just like lists.
The main difference between the tuples and the lists is that the tuples cannot be changed
unlike lists. Tuples use parentheses, whereas lists use square brackets .
Creating a tuple is as simple as putting different comma-separated values. Optionally, you can put
these comma-separated values between parentheses also.
For example-
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
The empty tuple is written as two parentheses containing nothing.
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is only one
value.
tup1 = (50,) Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so
on.
27. Accessing values in Tuples :
To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain the value available at that index.
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
When the above code is executed, it produces the following result-
tup1[0] : physics
tup2[1:5] : [2, 3, 4, 5]
28. Tuple Assignment :
Once in a while, it is useful to perform multiple assignments in a single statement and this can be
done with tuple assignment :
>>> a,b = 3,4
>>> print a 3
>>> print b 4
>>> a,b,c = (1,2,3),5,6
>>> print a (1, 2, 3)
>>> print b 5
>>> print c
The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned to its
respective variable. All the expressions on the right side are evaluated before any of the
assignments. This feature makes tuple assignment quite versatile. Naturally, the number of
variables on the left and the number of values on the right have to be the same:
Such statements can be useful shorthand for multiple assignment statements, but care should be
taken that it doesn’t make the code more difficult to read.
One example of tuple assignment that improves readibility is when we want to swap the values of
two variables. With conventional assignment statements, we have to use a temporary variable.
For example, to swap aand b:
29. Tuples as return values :
Functions can return tuples as return values. For example, we could write a function that swaps two
parameters :
def swap(x, y):
return y, x
Then we can assign the return value to a tuple with two variables:
a, b = swap(a, b)
Basic tuples operations, Concatenation, Repetition, in Operator, Iteration :
Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string.
30. Built-in Tuple Functions :
Python includes the following tuple functions-
31. Tuplelen()Method
Description
The len() method returns the number of elements in the tuple.
Syntax
Following is the syntax for len() method-
len(tuple)
Parameters
tuple - This is a tuple for which number of elements to be counted.
Return Value
This method returns the number of elements in the tuple.
tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc') print ("First tuple length : ", len(tuple1))
print ("Second tuple length : ", len(tuple2))
32. Tuplemax()Method
Description
The max() method returns the elements from the tuple with maximum value.
Syntax
Following is the syntax for max() method-
max(tuple)
Parameters
tuple - This is a tuple from which max valued element to be returned.
Return Value
This method returns the elements from the tuple with maximum value.
Example
The following example shows the usage of max() method.
When we run the above program, it produces the following result-
tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
print ("Max value element : ", max(tuple1)) print ("Max value element : ", max(tuple2)
33. Tuple min() Method
Description
The min() method returns the elements from the tuple with minimum value.
Syntax
Following is the syntax for min() method-
min(tuple)
Parameters
tuple - This is a tuple from which min valued element is to be returned.
Return Value
This method returns the elements from the tuple with minimum value.
tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
print ("min value element : ", min(tuple1)) print ("min value element : ", min(tuple2))
34. Tupletuple()Method
Description
The tuple() method converts a list of items into tuples.
Syntax
Following is the syntax for tuple() method-
tuple( seq )
Parameters
seq - This is a tuple to be converted into tuple.
Return Value
This method returns the tuple.
list1= ['maths', 'che', 'phy', 'bio'] tuple1=tuple(list1)
print ("tuple elements : ", tuple1)
o/p
tuple elements : ('maths', 'che', 'phy', 'bio')
35. Dictionary
Each key is separated from its value by a colon (:), the items are separated by commas, and
the whole thing is enclosed in curly braces. An empty dictionary without any items is written
with just two curly braces, like this:
{ }.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be
of any type, but the keys must be of an immutable data type such as strings, numbers, or
tuples.
Accessing Values in a dictionary :
To access dictionary elements, you can use the familiar square brackets along with the key to obtain its
value. Following is a simple example.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
o/p
dict['Name']: Zara
dict['Age']: 7
36. Updating Dictionary :
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing
entry as shown in a simple example given below.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age'] = 8; # update existing entry dict['School'] = "DPS School" # Add new
entry
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
o/p
dict['Age']: 8 dict['School']: DPS School
----------------------------------------------------------------------------------------------------------------------------------
Deleting Elements from Dictionary :
You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete
entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a simple example-
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name' dict.clear() # remove all entries in dict del dict # delete entire dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Note: An exception is raised because after del dict, the dictionary does not exist anymore.
37. Properties of Dictionary keys :
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-
defined objects. However, same is not true for the keys.
There are two important points to remember about dictionary keys-
A. More than one entry per key is not allowed. This means no duplicate key is allowed. When duplicate
keys are encountered during assignment, the last assignment wins.
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print ("dict['Name']: ", dict['Name'])
o/p
dict['Name']: Manni
B. Keys must be immutable. This means you can use strings, numbers or tuples as dictionary keys but
something like ['key'] is not allowed.
dict = {['Name']: 'Zara', 'Age': 7}
print ("dict['Name']: ", dict['Name'])
o/p
Traceback (most recent call last): File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7}
TypeError: list objects are unhashable
38. Operations in Dictionary :
The del statement removes a key-value pair from a dictionary. For example, the following
dictionary
contains the names of various fruits and the number of each fruit in stock:
>>> del inventory["pears"]
>>> print inventory
{’oranges’: 525, ’apples’: 430, ’bananas’: 312}
Or if we’re expecting more pears soon, we might just change the value associated with pears:
>>> inventory["pears"] = 0
>>> print inventory
{’oranges’: 525, ’apples’: 430, ’pears’: 0, ’bananas’: 312}
The len function also works on dictionaries; it returns the number of key-value pairs:
>>> len(inventory) 4
39. Built-In Dictionary Functions & Methods :
Python includes the following dictionary functions-
40. Dictionarylen()Method
Description
The method len() gives the total length of the dictionary. This would be equal to the number of
items in the dictionary.
Syntax
Following is the syntax for len() method-
len(dict)
Example
The following example shows the usage of len() method.
#!/usr/bin/python3
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'} print ("Length : %d" % len (dict))
When we run the above program, it produces the following result-
Length : 3
41. Dictionarystr()Method
Description
The method str() produces a printable string representation of a dictionary.
Syntax
Following is the syntax for str() method −
str(dict)
Parameters
dict - This is the dictionary.
Return Value
This method returns string representation.
Example
The following example shows the usage of str() method.
#!/usr/bin/python3
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'} print ("Equivalent String : %s" % str (dict))
Equivalent String : {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
42. Dictionary type() Method
Description
The method type() returns the type of the passed variable. If passed variable is dictionary then
it would return a dictionary type.
Syntax
Following is the syntax for type() method-
type(dict)
Parameters
dict - This is the dictionary.
Return Value
This method returns the type of the passed variable.
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'} print ("Variable Type : %s" % type (dict))
o/p
Variable Type : <type 'dict'>
45. Dictionaryclear()Method
Description
The method clear() removes all items from the dictionary.
Syntax
Following is the syntax for clear() method-
dict.clear()
Parameters
NA
Return Value
This method does not return any value.
Example :
dict = {'Name': 'Zara', 'Age': 7} print ("Start Len : %d" % len(dict)) dict.clear()
print ("End Len : %d" % len(dict))
o/p
Start Len : 2
End Len : 0
46. Dictionary copy() Method
Description
The method copy() returns a shallow copy of the dictionary.
Syntax
Following is the syntax for copy() method-
dict.copy()
Parameters
NA
Return Value
This method returns a shallow copy of the dictionary.
dict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'} dict2 = dict1.copy()
print ("New Dictionary : ",dict2)
o/p:
New dictionary : {'Name': 'Manni', 'Age': 7, 'Class':'First'}
47. NOTE:
Python provides two types of copy i.e. 1)shallow 2)deep
Shallow Copy
A shallow copy creates a new object which stores the reference of the original elements.
So, a shallow copy doesn't create a copy of nested objects, instead it just copies the reference
of nested objects. This means, a copy process does not recurse or create copies of nested
objects itself.
---------------------------------------------------------------------------------------------------
Deep Copy
A deep copy creates a new object and recursively adds the copies of nested objects present in
the original elements.
The deep copy creates independent copy of original object and all its nested objects.
48. Dictionary fromkeys() Method :
Description
The method fromkeys() creates a new dictionary with keys from seq and values set to value.
Syntax
Following is the syntax for fromkeys() method-
dict.fromkeys(seq[, value]))
Parameters
• seq - This is the list of values which would be used for dictionary keys preparation.
• value - This is optional, if provided then value would be set to thisvalue
Return Value
This method returns the list.
Example:
seq = ('name', 'age', 'sex') dict = dict.fromkeys(seq)
print ("New Dictionary : %s" % str(dict)) dict = dict.fromkeys(seq, 10)
print ("New Dictionary : %s" % str(dict)
49. Dictionary get() Method
Description
The method get() returns a value for the given key. If the key is not available then returns
default value None.
Syntax
Following is the syntax for get() method-
dict.get(key, default=None)
Parameters
• key - This is the Key to be searched in the dictionary.
• default - This is the Value to be returned in case key does not exist.
Return Value
This method returns a value for the given key. If the key is not available, then returns default
value as None.
dict = {'Name': 'Zara', 'Age': 27}
print ("Value : %s" % dict.get('Age'))
print ("Value : %s" % dict.get('Sex', "NA"))
50. Dictionary items() Method
Description
The method items() returns a list of dict's (key, value) tuple pairs.
Syntax :
Following is the syntax for items() method-
dict.items()
Parameters
NA
Return Value
This method returns a list of tuple pairs.
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.items())
o/p
Value : [('Age', 7), ('Name', 'Zara')]
51. Dictionary keys() Method :
Description
The method keys() returns a list of all the available keys in the dictionary.
Syntax
Following is the syntax for keys() method-
dict.keys()
Parameters
NA
Return Value
This method returns a list of all the available keys in the dictionary.
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.keys())
o/p
Value : ['Age', 'Name']
52. Dictionary setdefault() Method :
The method setdefault() is similar to get(), but will set dict[key]=default if the key is not
already in dict.
Syntax
Following is the syntax for setdefault() method-
dict.setdefault(key, default=None)
Parameters
• key - This is the key to be searched.
• default - This is the Value to be returned in case key is not found.
Return Value
This method returns the key value available in the dictionary and if given key is not available
then it will return provided default value.
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.setdefault('Age', None)) print ("Value : %s" % dict.setdefault('Sex',
None)) print (dict)
53. Dictionary update() Method
Description
The method update() adds dictionary dict2's key-values pairs in to dict. This function does not
return anything.
Syntax
Following is the syntax for update() method-
dict.update(dict2)
Parameters
dict2 - This is the dictionary to be added into dict.
Return Value
This method does not return any value.
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' } dict.update(dict2)
print ("updated dict : ", dict)
o/p
updated dict : {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}
54. Dictionaryvalues()Method
Description
The method values() returns a list of all the values available in a given dictionary.
Syntax
Following is the syntax for values() method-
dict.values()
Parameters
NA
Return Value
This method returns a list of all the values available in a given dictionary.
Example
The following example shows the usage of values() method.
#!/usr/bin/python3
dict = {'Sex': 'female', 'Age': 7, 'Name': 'Zara'} print ("Values : ", list(dict.values()))
When we run above program, it produces following result-
Values : ['female', 7, 'Zara']
55. Files
Python provides basic functions and methods necessary to manipulate files by default. You can do
most of the file manipulation using a file object.
The open Function
Before you can read or write a file, you have to open it using Python's built-in open() function. This
function creates a file object, which would be utilized to call other support methods associated with
it.
Syntax
file object = open(file_name [, access_mode][, buffering])
Here are parameter details-
file_name: The file_name argument is a string value that contains the name of the file that you
want to access.
access_mode: The access_mode determines the mode in which the file has to be opened, i.e.,
read, write, append, etc.
A complete list of possible values is given below in the table. This is an optional parameter and the
default file access mode is read (r).
buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is 1,
line buffering is performed while accessing a file. If you specify the buffering value as an integer
greater than 1, then buffering action is performed with the indicated buffer size. If negative, the
buffer size is the system default (default behavior).
58. The File Object Attributes :
Once a file is opened and you have one file object, you can get various information related to
that file.
Here is a list of all the attributes related to a file object-
Note: softspace attribute is not supported in Python 3.x
59. The close() Method
The close() method of a file object flushes any unwritten information and closes the file object,
after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another
file. It is a good practice to use the close() method to close a file.
Syntax
fileObject.close();
Example
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
# Close opened file fo.close()
This produces the following result-
Name of the file: foo.txt
60. Reading and Writing Files
The file object provides a set of access methods to make our lives easier. We would see how to
use read() and write() methods to read and write files.
-----------------------------------------------------------------------------------------------------------
-
The write() Method
The write() method writes any string to an open file. It is important to note that Python strings
can have binary data and not just text.
The write() method does not add a newline character ('n') to the end of the string-
Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
# Open a file
fo = open("foo.txt", "w")
fo.write( "Python is a great language.nYeah its great!!n")
# Close opend file fo.close()
The above method would create foo.txt file and would write given content in that file and finally it would
close that file. If you would open this file, it would have the following content-
61. The read() Method
The read() method reads a string from an open file. It is important to note that Python strings
can have binary data apart from the text data.
Syntax
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file. This method
starts reading from the beginning of the file and if count is missing, then it tries to read as much
as possible, maybe until the end of file.
Example
Let us take a file foo.txt, w
# Open a file
fo = open("foo.txt", "r+") str = fo.read(10)
print ("Read String is : ", str)
# Close opened file fo.close() which we created above.
62. File Positions :
The tell() method tells you the current position within the file; in other words, the
next read or write will occur at that many bytes from the beginning of the file.
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, the beginning of the file is used as the reference position. If it is
set to 1, the current position is used as the reference position. If it is set to 2 then the
end of the file would b
63. # Open a file
fo = open("foo.txt", "r+") str = fo.read(10)
print ("Read String is : ", str)
# Check current positione taken as the reference position.
position = fo.tell()
print ("Current file position : ", position)
# Reposition pointer at the beginning once again position = fo.seek(0, 0)
str = fo.read(10)
print ("Again read String is : ", str)
# Close opened file fo.close()
This produces the following result-
Read String is : Python is Current file position : 10
Again read String is : Python is
64. Renaming and Deleting Files
Python os module provides methods that help you perform file-processing operations, such as
renaming and deleting files.
The rename()Method
The rename() method takes two arguments, the current filename and the new filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is an example to rename an existing file test1.txt-
#!/usr/bin/python3 import os
# Rename a file from test1.txt to test2.txt os.rename( "test1.txt", "test2.txt" )
65. The remove() Method
You can use the remove() method to delete files by supplying the name of the file to be
deleted as the argument.
Syntax
os.remove(file_name)
Example
Following is an example to delete an existing file test2.txt-
#!/usr/bin/python3 import os
# Delete file test2.txt os.remove("text2.txt")
66. Directories :
All files are contained within various directories, and Python has no problem handling these
too.
The os module has several methods that help you create, remove, and change directories.
The mkdir() Method
You can use the mkdir() method of the os module to create directories in the current directory.
You need to supply an argument to this method, which contains the name of the directory to
be created.
Syntax
os.mkdir("newdir")
#!/usr/bin/python3 import os
# Create a directory "test" os.mkdir("test")
67. The chdir() Method
You can use the chdir() method to change the current directory.
The chdir() method takes an argument, which is the name of the directory that you want to
make the current directory.
Syntax
os.chdir("newdir")
Example
Following is an example to go into "/home/newdir" directory-
#!/usr/bin/python3 import os
# Changing a directory to "/home/newdir" os.chdir("/home/newdir")
68. The getcwd() Method
The getcwd() method displays the current working directory.
Syntax :
os.getcwd()
#!/usr/bin/python3 import os
# This would give location of the current directory os.getcwd()
---------------------------------------------------------------------------------------------------------
The rmdir() Method
The rmdir() method deletes the directory, which is passed as an argument in the method.
Before removing a directory, all the contents in it should beremoved.
Syntax :
os.rmdir('dirname')
import os
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )
69. Exceptions :
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception. An exception is a Python object that
represents an error.
When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits.
Python provides two types of exceptions i.e. 1)built-in 2)user defined
Built-in Exceptions
:
73. Handling Exceptions :
If you have some suspicious code that may raise an exception, you can defend your program
by placing the suspicious code in a try: block. After the try: block, include an except:
statement, followed by a block of code which handles the problem as elegantly as possible.
Syntax
Here is simple syntax of
try....except...else blocks-
74. Here are few important points about the above-mentioned syntax-
• A single try statement can have multiple except statements. This is useful when the try block
contains statements that may throw different types of exceptions.
• You can also provide a generic except clause, which handles any exception.
• After the except clause(s), you can include an else-clause. The code in the else- block
executes if the code in the try: block does not raise an exception.
• The else-block is a good place for code that does not need the try: block's protection.
75. Example:
#!/usr/bin/python3
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can't find file or read data")
else:
print ("Written content in the file successfully") fh.close()
76. Exception with Arguments :
An exception can have an argument, which is a value that gives additional
information about the problem. The contents of the argument vary by exception.
You capture an exception's argument by supplying a variable in the except clause as
follows-
If you write the code to handle a single exception, you can have a variable follow the name of the
exception in the except statement. If you are trapping multiple exceptions, you can have a
variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the exception. The
variable can receive a single value or multiple values in the form of a tuple. This tuple usually
contains the error string, the error number, and an errorlocation.
77. Example
Following is an example for a single exception-
#!/usr/bin/python3
# Define a function here. def temp_convert(var): try:
returnint(var)
except ValueError as Argument:
print("The argument does not contain numbersn",Argument)
# Call above function here. temp_convert("xyz")
o/p
The argument does not contain numbers invalid literal for int() with base 10: 'xyz'
78. User-defined Exceptions :
Python also allows you to create your own exceptions byderiving classes fromthe standard
built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed from
RuntimeError. This is useful when you need to display more specific information when an
exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The
variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def init (self, arg):
self.args = arg
So once you have defined the above class, you can raise the exception as follows-
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
79. QUICK REVISION OF UNIT III :
A list is an ordered set of values, where each value is identified by an index.
Important thing about a list is that the items in a list need not be of the same type.
Lists are mutable .
An assignment to an element of a list is called item assignment
Tuple are very similar to lists with only difference that element values of a tuple can
not be changed and tuple elements are put between parentheses instead of square
bracket.
append method used to add element in list at last position .
tuple is a sequence of immutable Python objects.
Dictionary :Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly braces.
More than one entry per key is not allowed.
Keys must be immutable.
An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions.
Python provides two types of exceptions i.e. 1)built-in 2)user defined
80. VISIT
https://www.profajaypashankar.com
For more study material and notes .
VISIT
https://www.youtube.com/channel/UCu4Bd22zM6RpvHWC9YHBh5Q?view_as=subscriber
For more lectures .
VISIT : FOR PRACTICAL MANUAL
https://www.profajaypashankar.com/python-programming-practical-manual/
Password:STUDYHARD