Unit 3
Unit 3
Python List
In Python, the sequence of various data types is stored in a list. A list is a
collection of different kinds of values or items. Since Python lists are mutable,
we can change their elements after forming. The comma (,) and the square
brackets [enclose the List's items] serve as separators.
Although six Python data types can hold sequences, the List is the most
common and reliable form. A list, a type of sequence data, is used to store the
collection of data. Tuples and Strings are two similar data formats for
sequences.
List Declaration
Code
1. # a simple list
2. list1 = [1, 2, "Python", "Program", 15.9]
3. list2 = ["Amy", "Ryan", "Henry", "Emma"]
4.
5. # printing the list
6. print(list1)
7. print(list2)
8.
9. # printing the type of list
10.print(type(list1))
11.print(type(list2))
Output:
Characteristics of Lists
Code
1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
3. b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
4. a == b
Output:
False
The indistinguishable components were remembered for the two records;
however, the subsequent rundown changed the file position of the fifth
component, which is against the rundowns' planned request. False is returned
when the two lists are compared.
Code
1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
3. b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
4. a == b
Output:
True
Code
Output:
printing employee data...
Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class ' list '> <class ' list '> <class ' list '> <class ' list '> <class ' list '>
The indexing procedure is carried out similarly to string processing. The slice
operator [] can be used to get to the List's components.
The index ranges from 0 to length -1. The 0th index is where the List's first
element is stored; the 1st index is where the second element is stored, and so
on.
We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
Code
1. list = [1,2,3,4,5,6,7]
2. print(list[0])
3. print(list[1])
4. print(list[2])
5. print(list[3])
6. # Slicing the elements
7. print(list[0:6])
8. # By default, the index value is 0 so its starts from the 0th element and go for
index -1.
9. print(list[:])
10.print(list[2:5])
11.print(list[1:6:2])
Output:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
Let's have a look at the following example where we will use negative
indexing to access the elements of the list.
Code
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
Due to their mutability and the slice and assignment operator's ability to
update their values, lists are Python's most adaptable data structure. Python's
append() and insert() methods can also add values to a list.
Consider the following example to update the values inside the List.
Code
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
The list elements can also be deleted by using the del keyword. Python also
provides us the remove() method if we do not know which element is to be
deleted from the list.
Code
1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
3. # It will assign value to the value to second index
4. list[2] = 10
5. print(list)
6. # Adding multiple element
7. list[1:3] = [89, 78]
8. print(list)
9. # It will add value at the end of the list
10.list[-1] = 25
11.print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
The concatenation (+) and repetition (*) operators work in the same way as
they were working with the strings. The different operations of list are
1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership
1. Repetition
The redundancy administrator empowers the rundown components to be
rehashed on different occasions.
Code
1. # repetition of list
2. # declaring the list
3. list1 = [12, 14, 16, 18, 20]
4. # repetition operator *
5. l = list1 * 2
6. print(l)
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
2. Concatenation
Code
3. Length
Code
4. Iteration
Code
12
14
16
39
40
5. Membership
Code
False
False
False
True
True
True
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four
strings, which can be iterated as follows.
Code
1. # iterating a list
2. list = ["John", "David", "James", "Jonathan"]
3. for i in list:
4. # The i variable will iterate over the elements of the List and contains each
element in each iteration.
5. print(i)
Output:
John
David
James
Jonathan
Adding Elements to the List
The append() function in Python can add a new item to the List. In any case,
the annex() capability can enhance the finish of the rundown.
Code
Example -
Code
1. list = [0,1,2,3,4]
2. print("printing original list: ");
3. for i in list:
4. print(i,end=" ")
5. list.remove(2)
6. print("\nprinting the list after the removal of first element...")
7. for i in list:
8. print(i,end=" ")
Output:
Python provides the following built-in functions, which can be used with the
lists.
1. len()
2. max()
3. min()
len( )
Code
Max( )
Code
782
Min( )
Code
103
1. list1 = [1,2,2,3,55,98,65,65,13,29]
2. # Declare an empty list that will store unique values
3. list2 = []
4. for i in list1:
5. if i not in list2:
6. list2.append(i)
7. print(list2)
Output:
Python Set
A Python set is the collection of the unordered items. Each element in the set
must be unique, immutable, and the sets remove the duplicate elements. Sets
are mutable which means we can modify it after its creation.
Creating a set
It can contain any type of element such as integer, float, tuple etc. But mutable
elements (list, dictionary, set) can't be a member of set. Consider the following
example.
1. # Creating a set which have immutable elements
2. set1 = {1,2,3, "JavaTpoint", 20.5, 14}
3. print(type(set1))
4. #Creating a set which have mutable element
5. set2 = {1,2,3,["Javatpoint",4]}
6. print(type(set2))
Output:
<class 'set'>
In the above code, we have created two sets, the set set1 have immutable
elements and set2 have one mutable element as a list. While checking the type
of set2, it raised an error, which means set can contain only immutable
elements.
Creating an empty set is a bit different because empty curly {} braces are also
used to create a dictionary as well. So Python provides the set() method used
without an argument to create an empty set.
<class 'dict'>
<class 'set'>
Let's see what happened if we provide the duplicate element to the set.
1. set5 = {1,2,4,4,5,8,9,9,10}
2. print("Return set with unique elements:",set5)
Output:
In the above code, we can see that set5 consisted of multiple duplicate
elements when we printed it remove the duplicity from the set.
Python provides the add() method and update() method which can be used to
add some particular item to the set. The add() method is used to add a single
element whereas the update() method is used to add multiple elements to the
set. Consider the following example.
To add more than one item in the set, Python provides the update() method.
It accepts iterable as an argument.
Python provides the discard() method and remove() method which can be
used to remove the items from the set. The difference between these function,
using discard() function if the item does not exist in the set then the set remain
unchanged whereas remove() method will through an error.
Python provides also the remove() method to remove the item from the set.
Consider the following example to remove the items using remove() method.
We can also use the pop() method to remove the item. Generally, the pop()
method will always remove the last item but the set is unordered, we can't
determine which element will be popped from set.
Consider the following example to remove the item from the set using pop()
method.
Python provides the clear() method to remove all the items from the set.
Despite the fact that discard() and remove() method both perform the same
task, There is one main difference between discard() and remove().
If the key to be deleted from the set using discard() doesn't exist in the set, the
Python will not give the error. The program maintains its control flow.
On the other hand, if the item to be deleted from the set using remove() doesn't
exist in the set, the Python will raise an error.
Example-
To combine two or more sets into one set in Python, use the union() function.
All of the distinctive characteristics from each combined set are present in the
final set. As parameters, one or more sets may be passed to the union()
function. The function returns a copy of the set supplied as the lone parameter
if there is just one set. The method returns a new set containing all the different
items from all the arguments if more than one set is supplied as an argument.
Python also provides the union() method which can also be used to calculate
the union of two sets. Consider the following example.
1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1.union(Days2)) #printing the union of the sets
Output:
{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday',
'Saturday'}
Now, we can also make the union of more than two sets using the union()
function, for example:
Program:
{1, 2, 3, 4, 5}
To discover what is common between two or more sets in Python, apply the
intersection() function. Only the items in all sets being compared are included
in the final set. One or more sets can also be used as the intersection() function
parameters. The function returns a copy of the set supplied as the lone
parameter if there is just one set. The method returns a new set that only
contains the elements in all the compared sets if multiple sets are supplied as
arguments.
The intersection of two sets can be performed by the and & operator or
the intersection() function. The intersection of the two sets is given as the set
of the elements that common in both sets.
Consider the following example.
{'Monday', 'Tuesday'}
{'Martin', 'David'}
Example 3:
1. set1 = {1,2,3,4,5,6,7}
2. set2 = {1,2,20,32,5,9}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
{1,2,5}
For Example:
Program
{3}
The intersection_update() method removes the items from the original set
that are not present in both the sets (all the sets if more than one are specified).
{'castle'}
The difference of two sets can be calculated by using the subtraction (-)
operator or intersection() method. Suppose there are two sets A and B, and
the difference is A-B that denotes the resulting set will be obtained that
element of A, which is not present in the set B.
{'Thursday', 'Wednesday'}
{'Thursday', 'Wednesday'}
In Python, the symmetric Difference between set1 and set2 is the set of
elements present in one set or the other but not in both sets. In other words,
the set of elements is in set1 or set2 but not in their intersection.
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a^b
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a.symmetric_difference(b)
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
Set comparisons
In Python, you can compare sets to check if they are equal, if one set is a subset
or superset of another, or if two sets have elements in common.
o ==: checks if two sets have the same elements, regardless of their order.
o !=: checks if two sets are not equal.
o <: checks if the left set is a proper subset of the right set (i.e., all
elements in the left set are also in the right set, but the right set has
additional elements).
o <=: checks if the left set is a subset of the right set (i.e., all elements in
the left set are also in the right set).
o >: checks if the left set is a proper superset of the right set (i.e., all
elements in the right set are also in the left set, but the left set has
additional elements).
o >=: checks if the left set is a superset of the right set (i.e., all elements
in the right set are also in the left).
Consider the following example.
True
False
False
FrozenSets
In Python, a frozen set is an immutable version of the built-in set data type. It
is similar to a set, but its contents cannot be changed once a frozen set is
created.
Frozen set objects are unordered collections of unique elements, just like sets.
They can be used the same way as sets, except they cannot be modified.
Because they are immutable, frozen set objects can be used as elements of
other sets or dictionary keys, while standard sets cannot.
One of the main advantages of using frozen set objects is that they are
hashable, meaning they can be used as keys in dictionaries or as elements of
other sets. Their contents cannot change, so their hash values remain constant.
Standard sets are not hashable because they can be modified, so their hash
values can change.
Frozen set objects support many of the assets of the same operation, such as
union, intersection, Difference, and symmetric Difference. They also support
operations that do not modify the frozen set, such as len(), min(), max(), and
in.
1. Frozenset = frozenset([1,2,3,4,5])
2. print(type(Frozenset))
3. print("\nprinting the content of frozen set...")
4. for i in Frozenset:
5. print(i);
6. Frozenset.add(6) #gives an error since we cannot change the content of Froz
enset after creation
Output:
<class 'frozenset'>
If we pass the dictionary as the sequence inside the frozenset() method, it will
take only the keys from the dictionary and returns a frozenset that contains the
key of the dictionary as its elements.
<class 'dict'>
<class 'frozenset'>
Name
Country
ID
Example - 1: Write a program to remove the given number from the set.
1. my_set = {1,2,3,4,5,6,12,24}
2. n = int(input("Enter the number you want to remove"))
3. my_set.discard(n)
4. print("After Removing:",my_set)
Output:
1. set1 = set([1,2,4,"John","CS"])
2. set1.update(["Apple","Mango","Grapes"])
3. print(set1)
Output:
{56, 23}
1. set1 = {23,44,56,67,90,45,"Javatpoint"}
2. set2 = {13,23,56,76,"Sachin"}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
Above code raised an error because frozensets are immutable and can't be
changed after creation.
Example - 6: Write the program to find the issuperset, issubset and superset.
1. set1 = set(["Peter","James","Camroon","Ricky","Donald"])
2. set2 = set(["Camroon","Washington","Peter"])
3. set3 = set(["Peter"])
4.
5. issubset = set1 >= set2
6. print(issubset)
7. issuperset = set1 <= set2
8. print(issuperset)
9. issubset = set3 <= set2
10.print(issubset)
11.issuperset = set2 >= set3
12.print(issuperset)
Output:
False
False
True
True
Python Tuples
A comma-separated group of items is called a Python triple. The ordering,
settled items, and reiterations of a tuple are to some degree like those of a
rundown, but in contrast to a rundown, a tuple is unchanging.
The main difference between the two is that we cannot alter the components
of a tuple once they have been assigned. On the other hand, we can edit the
contents of a list.
Example
Forming a Tuple:
Any number of items, including those with various data types (dictionary,
string, float, list, etc.), can be contained in a tuple.
Code
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Parentheses are not necessary for the construction of multiples. This is known
as triple pressing.
Code
Code
<class 'str'>
<class 'tuple'>
<class 'tuple'>
Indexing
Indexing We can use the index operator [] to access an object in a tuple, where
the index starts at 0.
The indices of a tuple with five items will range from 0 to 4. An Index Error
will be raised assuming we attempt to get to a list from the Tuple that is outside
the scope of the tuple record. An index above four will be out of range in this
scenario.
Because the index in Python must be an integer, we cannot provide an index
of a floating data type or any other type. If we provide a floating index, the
result will be TypeError.
The method by which elements can be accessed through nested tuples can be
seen in the example below.
Code
Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6
o Negative Indexing
Python's sequence objects support negative indexing.
The last thing of the assortment is addressed by - 1, the second last thing by -
2, etc.
Code
Slicing
Tuple slicing is a common practice in Python and the most common way for
programmers to deal with practical issues. Look at a tuple in Python. Slice a
tuple to access a variety of its elements. Using the colon as a straightforward
slicing operator (:) is one strategy.
To gain access to various tuple elements, we can use the slicing operator colon
(:).
Code
Deleting a Tuple
Code
Tuple Methods
Like the list, Python Tuples is a collection of immutable objects. There are a
few ways to work with tuples in Python. With some examples, this essay will
go over these two approaches in detail.
o Count () Method
The times the predetermined component happens in the Tuple is returned by
the count () capability of the Tuple.
Code
1. # Creating tuples
2. T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
3. T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
4. # counting the appearance of 3
5. res = T1.count(2)
6. print('Count of 2 in T1 is:', res)
7. # counting the appearance of java
8. res = T2.count('java')
9. print('Count of Java in T2 is:', res)
Output:
Count of 2 in T1 is: 5
Count of java in T2 is: 2
Index() Method:
The Index() function returns the first instance of the requested element from
the Tuple.
Parameters:
1. # Creating tuples
2. Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
3. # getting the index of 3
4. res = Tuple_data.index(3)
5. print('First occurrence of 1 is', res)
6. # getting the index of 3 after 4th
7. # index
8. res = Tuple_data.index(3, 4)
9. print('First occurrence of 1 after 4th index is:', res)
Output:
First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6
Code
True
False
False
True
Code
Python
Tuple
Ordered
Immutable
Changing a Tuple
Code
The + operator can be used to combine multiple tuples into one. This
phenomenon is known as concatenation.
Code
Python Dictionary
Dictionaries are a useful data structure for storing data in Python because they
are capable of imitating real-world data arrangements where a certain value
exists for a given key.
Curly brackets are the simplest way to generate a Python dictionary, although
there are other approaches as well. With many key-value pairs surrounded in
curly brackets and a colon separating each key from its value, the dictionary
can be built. (:). The following provides the syntax for defining the dictionary.
Syntax:
Code
<class 'dict'>
printing Employee data ....
{'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}
Python provides the built-in function dict() method which is also used to
create the dictionary.
Code
Empty Dictionary:
{}
To access data contained in lists and tuples, indexing has been studied. The
keys of the dictionary can be used to obtain the values because they are unique
from one another. The following method can be used to access dictionary
values.
Code
ee["Company"])
Output
<class 'dict'>
printing Employee data ....
Name : Dev
Age : 20
Salary : 45000
Company : WIPRO
Python provides us with an alternative to use the get() method to access the
dictionary values. It would give the same result as given by the indexing.
The dictionary is a mutable data type, and utilising the right keys allows you
to change its values. Dict[key] = value and the value can both be modified. An
existing value can also be updated using the update() method.
Note: The value is updated if the key-value pair is already present in the
dictionary. Otherwise, the dictionary's newly added keys.
Let's see an example to update the dictionary values.
Example - 1:
Code
Empty Dictionary:
{}
Example - 2:
Code
<class 'dict'>
printing Employee data ....
Employee = {"Name": "Dev", "Age": 20,
"salary":45000,"Company":"WIPRO"} Enter the details of the new
employee....
Name: Sunny
Age: 38
Salary: 39000
Company:Hcl
printing the new data
{'Name': 'Sunny', 'Age': 38, 'salary': 39000, 'Company': 'Hcl'}
The items of the dictionary can be deleted by using the del keyword as given
below.
Code
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined.
The last print statement in the above code, it raised an error because we tried
to print the Employee dictionary that already deleted.
Code
1. # Creating a Dictionary
2. Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}
3. # Deleting a key
4. # using pop() method
5. pop_key = Dict1.pop(2)
6. print(Dict1)
Output
Iterating Dictionary
Example 1
Code
Name
Age
salary
Company
Example 2
Code
John
29
25000
WIPRO
Example - 3
Code
1. #for loop to print the values of the dictionary by using values() method.
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIP
RO"}
3. for x in Employee.values():
4. print(x)
Output
John
29
25000
WIPRO
Example 4
Code
1. #for loop to print the items of the dictionary by using items() method
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIP
RO"}
3. for x in Employee.items():
4. print(x)
Output
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'WIPRO')
1. In the dictionary, we cannot store multiple values for the same keys. If we
pass more than one value for a single key, then the value which is last assigned
is considered as the value of the key.
Code
1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO
","Name":
2. "John"}
3. for x,y in Employee.items():
4. print(x,y)
Output
Name John
Age 29
Salary 25000
Company WIPRO
2. The key cannot belong to any mutable object in Python. Numbers, strings,
or tuples can be used as the key, however mutable objects like lists cannot be
used as the key in a dictionary.
Code
The built-in Python dictionary methods are listed below, along with a brief
description.
o len()
The dictionary's length is returned via the len() function in Python. The string
is lengthened by one for each key-value pair.
Code
o any()
Like how it does with lists and tuples, the any() method returns True indeed if
one dictionary key does have a Boolean expression that evaluates to True.
Code
True
o all()
Unlike in any() method, all() only returns True if each of the dictionary's keys
contain a True Boolean value.
Code
False
o sorted()
Like it does with lists and tuples, the sorted() method returns an ordered series
of the dictionary's keys. The ascending sorting has no effect on the original
Python dictionary.
Code
1. dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}
2. sorted(dict)
Output
[ 1, 5, 7, 8]
The built-in python dictionary methods along with the description and Code
are given below.
o clear()
It is mainly used to delete all the items of the dictionary.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # clear() method
4. dict.clear()
5. print(dict)
Output
{}
o copy()
It returns a shallow copy of the dictionary which is created.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # copy() method
4. dict_demo = dict.copy()
5. print(dict_demo)
Output
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
o pop()
It mainly eliminates the element using the defined key.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # pop() method
4. dict_demo = dict.copy()
5. x = dict_demo.pop(1)
6. print(x)
Output
popitem()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # popitem() method
4. dict_demo.popitem()
5. print(dict_demo)
Output
o keys()
It returns all the keys of the dictionary.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # keys() method
4. print(dict_demo.keys())
Output
dict_keys([1, 2, 3, 4, 5])
o items()
It returns all the key-value pairs as a tuple.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # items() method
4. print(dict_demo.items())
Output
o get()
It is used to get the value specified for the passed key.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # get() method
4. print(dict_demo.get(3))
Output
o update()
It mainly updates all the dictionary by adding the key-value pair of dict2 to
this dictionary.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # update() method
4. dict_demo.update({3: "TCS"})
5. print(dict_demo)
Output
o values()
It returns all the values of the dictionary with respect to given input.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # values() method
4. print(dict_demo.values())
Output
File handling
File handling in Python is a crucial skill for managing data storage and
retrieval. Here’s a quick overview of how to work with files in Python:
1. **Opening a File**:
Use the `open()` function to open a file. You can specify the mode:
- `'r'`: Read (default mode)
- `'w'`: Write (creates a new file or truncates an existing one)
- `'a'`: Append (adds to an existing file)
- `'b'`: Binary mode (for non-text files)
```python
file = open('example.txt', 'r')
```
```python
content = file.read()
```
3. **Writing to a File**:
Use the `write()` or `writelines()` methods to write data.
```python
with open('example.txt', 'w') as file:
file.write("Hello, World!")
```
4. **Closing a File**:
Always close the file after operations to free up system resources.
```python
file.close()
```
```python
with open('example.txt', 'r') as file:
content = file.read()
```
```python
# Writing to a file
with open('example.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("Welcome to file handling in Python.")
To handle errors like file not found, you can use a `try` and `except` block:
```python
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("The file does not exist.")
```
```python
# Writing a binary file
with open('image.png', 'wb') as file:
file.write(binary_data)
If you're using simple structures like lists or dictionaries, you can write them
to a text file in a readable format:
```python
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
For tabular data, the CSV (Comma-Separated Values) format is very useful.
You can use the `csv` module:
```python
import csv
data = [
["Name", "Age", "City"],
["Alice", 30, "New York"],
["Bob", 25, "Los Angeles"],
]
```python
import json
data = {
"people": [
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "Los Angeles"}
]
}
If you want to serialize and save Python objects directly, you can use the
`pickle` module. This is useful for more complex Python objects:
```python
import pickle
data = {
"name": "Alice",
"age": 30,
"hobbies": ["reading", "hiking", "coding"]
}
```python
print("Hello, World!"
```
Example:
```python
result = 10 / 0 # Raises ZeroDivisionError
```
Python provides a robust way to handle exceptions using the `try`, `except`,
`else`, and `finally` blocks:
You can use a `try` block to wrap code that may raise an exception and an
`except` block to handle it.
```python
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
```
```python
try:
# some code that may raise an exception
result = int("abc") # Raises ValueError
except (ValueError, TypeError) as e:
print(f"An error occurred: {e}")
```
The `else` block runs if the `try` block does not raise an exception:
```python
try:
result = 10 / 2
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(f"Result is {result}")
```
```python
try:
file = open('data.txt', 'r')
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close() # This will run no matter what
```
### Raising Exceptions
You can also raise exceptions intentionally using the `raise` keyword:
```python
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
return age
try:
check_age(-5)
except ValueError as e:
print(e)
```
You can define your own exceptions by subclassing the built-in `Exception`
class:
```python
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error.")
except CustomError as e:
print(e)
```
Handling exception
```python
try:
# Code that may raise an exception
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
# Code that runs if the specified exception occurs
print("You can't divide by zero!")
```
```python
try:
# Some code that may raise an exception
value = int("abc") # This will raise a ValueError
except (ValueError, TypeError) as e:
print(f"An error occurred: {e}")
```
The `else` block runs if the `try` block does not raise any exceptions:
```python
try:
result = 10 / 2
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(f"Result is {result}")
```
The `finally` block will execute no matter what, whether an exception was
raised or not. This is useful for cleanup tasks, like closing files or releasing
resources:
```python
try:
file = open('data.txt', 'r')
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close() # This will run regardless of whether an exception occurred
```
You can raise exceptions intentionally using the `raise` keyword, which is
useful for enforcing conditions in your code:
```python
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
return age
try:
check_age(-5)
except ValueError as e:
print(e)
```
You can create your own exception classes by subclassing the built-in
`Exception` class. This allows you to define specific error conditions for
your application:
```python
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error.")
except CustomError as e:
print(e)
```
### Best Practices
```python
try:
# Some code
except ValueError:
# Handle ValueError
```
3. **Use Finally for Cleanup**: Always use the `finally` block for actions
that must occur regardless of success or failure (like closing files).