Lab Manual Updated
Lab Manual Updated
ROLL NO:........................................................................
BRANCH:.........................................................................
SECTION:.........................................................................
YEAR:..............................................................................
SEMESTER: .....................................................................
Mr. D.S.Lavhkare +91-9607589982 Cedge Technologies Ltd.
PPS LAB Objectives:
Understand the basic concept of Python Programming, and its different modules that include
conditional and looping expressions, Arrays, Strings, Functions, and Structures.
Acquire knowledge aboutthe basic concept of writing aprogram.
Role of constants, variables, identifiers, operators, type conversion and other building blocks of
Python Language.
Use of conditional expressions and looping statements to solve problems associated with conditions
and repetitions.
Role of Functions involving the idea of modularity.
Programming using Python tool in Linux.
LAB PREPARATION:
The remainder of this lab manual contains some helpful information on the software and hardware
systems you will be using this semester. This lab manual should be at your side whenever you are
logged in and doing work for this course, either in a lab or for a homework assignment or for any
other reason.
Anaconda Installation:
Title:
To calculate salary of an employee given his basic pay (take as input from user). Calculate salary of
employee. Let HRA be 10 % of basic pay and TA be 5% of basic pay. Let employee pay
professional tax as 2% of total salary. Calculate salary payable after deductions.
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.
Problem Statement:
Outcomes:
1. Students will be able to demonstrate calculations of employee salary.
3. Students will be able to demonstrate different Operations on Available data of employee salary.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more
Theory:
Python Basics:
Python is an interpreted, high-level, general-purpose programming language. Created by Guido van
Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its
notable use of significant whitespace.
What is Basic salary?
Basic salary is the base income of an individual. It is a fixed part of one's compensation package.
A basic salary depends on the employee’s designation and also the industry in which the employee
works.
Basic salary is the amount paid to an employee before any extras are added or taken off, such as
reductions because of salary sacrifice schemes or an increase due to overtime or a bonus.
Allowances, such as internet for home-based workers or contributions to phone usage, would also
be added to the basic salary.
Allowances:
An allowance is an amount received by the employee for meeting service requirements. Allowances
are provided in addition to the basic salary and vary from company to company. Some common
types of allowances are shown below:
• HRA or House Rent Allowance: It is an amount paid out to employees by companies for
expenses related to rented accommodation.
• Leave Travel Allowance (LTA): LTA is the amount provided by the company to cover
domestic travel expenses of an employee. It does not include the expenses for food,
accommodation, etc. during the travel.
• Conveyance Allowance: This allowance is provided to employees to meet travel expenses
from residence to work.
• Dearness Allowance: DA is a living allowance paid to employees to tackle the effects of
inflation. It is applicable to government employees, public sector employees, and pensioners
only.
• Other such allowances are the special allowance, medical allowance, incentives, etc.
HRA:
HRA received is not fully exempt from tax. HRA that you can claim is the lowest of the following:
• The total amount received as the HRA from the employer in the financial year.
• Actual rent paid in the year – 10% of the basic salary in the year.
• 50% of the annual basic salary if staying in a metro city or 40% of the annual basic salary if
staying in a non-metro city.
Sample Example:
Python program to get employee wages and number of days worked from user and find Basic
Pay, DA, HRA, PF and Net Pay.
(Note HRA, DA and PF are 10%,5%and 12% of basicpay respectively.)
Sample Input 1:
300
30
Sample Output 1:
Basic Pay:3000
Solution:
days=float(input("Enter No Days Present:"))
wages=float(input("Enter wages per Day:"))
basic=wages*days;
HRA=basic*0.1;
DA=basic*0.05;
PF=basic*0.12;
netsalary=basic+HRA+DA-PF;
print("\nBasic:%lf \nHRA:%lf \nDA:%lf \nPF:%lf \nNet Salary:%lf" %
(basic,HRA,DA,PF,netsalary));
This python program is using if else statement to compute the gross salary from basic salary input.
Here we have two different logic's to compute gross salary. so we are using if and else statements.
def calcualte_gross_salary(basic_salary):
hra = 0;
da = 0;
# salary is less than 2500, hra and da is calculated using this logic, otherwise else logic.
if (basic_salary < 2500):
hra = (basic_salary * 10) / 100;
da = (basic_salary * 90) / 100;
else:
hra = 1000;
da = (basic_salary * 95) / 100;
Output:
$ python gross_salary.py
Conclusion:
Thus, we have successfully understood concept of salary calculation formulas and performed salary
calculation in python.
Title:
To accept N numbers from user. Compute and display maximum in list, minimum in list,
sum and average of numbers.
Objective:
Understand basic concepts of python programming language and try to solve list concepts related
programs.
Problem Statement:
Outcomes:
2. Students will be able to demonstrate different Operator & formulas on given list.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more
Theory:
What is list?
Python offers a range of compound datatypes often referred to as sequences. List is one of the most
frequently used and very versatile datatype used in Python.
[ ], separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
List Index
We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5
elements will have index from 0 to 4.
Trying to access an element other that this will raise an IndexError. The index must be an integer.
We can't use float or other types, this will result into TypeError.
Nested list are accessed using nested indexing.
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# my_list[4.0]
# Nested List
# Nested indexing
print(n_list[0][1])
# Output: 5print(n_list[1][3])
In this experiment, we will learn how to find the maximum and minimum number in a python list.
Python list can hold items of any data types. All items are separated by a comma and placed inside a
square bracket. We can access any item by using its index. The index starts at 0. The index for the
first element is 0, the index of the second element is 1 etc.
Here will show you how to find the maximum and minimum number in a list using a loop. All the
numbers will be entered by the user. The user will enter the list items one by one and our program
will read them.
First, we will ask the user to enter the total number count. Then using a for loop, we will read each
number and append them to the list. Finally, again using one more for loop, we will calculate the
maximum and minimum number and print out the result. Let’s take a look into the following sample
program first.
Explanation :
1. Create one empty list my_list. We are using one empty square bracket to create the empty list.
This is a list without any items.
2. Get the total number of elements the user is going to enter and save it in the count variable. This
is required because we will ask the user to enter each number one by one. If the value of count is 4,
the user will have to enter four numbers to add to the list.
3. Using a for loop, get the numbers and append it to the list my_list. For appending a number,
5. Create two variables to hold the minimum and maximum number. We are assigning the first
element of the list to both of these variables first. We will update these variables on the next step.
On this step, we are assuming that the minimum and maximum value of the list is equal to the first
element of the list. We will compare this value with all other elements of the list one by one and
update them if required.
6. Run one for loop on the list again. For each number, check if it is less than the minimum number.
If yes, assign the minimum value holding variable to this number. Similarly, update the maximum
value if the number is more than the current maximum.
7. After the list is completed reading, print out both maximum and minimum numbers.
Algorithm:
1.Create an empty list named l
2.Read the value of n
3.Read the elements of the list until n
4.Assign l[0] as maxno
5.If l[i]>maxno then set maxno=l[i]
6.Increment i by 1
7.Repeat steps 5-6 until i<n
8.Print the value of maximum number
Program:
l=[]
n=int(input("enter the upper limit"))
for i in range(0,n):
a=int(input("enter the numbers"))
l.append(a)
maxno=l[0]
for i in range(0,len(l)):
if l[i]>maxno:
maxno=l[i]
print("The maximum number is %d"%maxno)
Title:
To accept student’s five courses marks and compute his/her result. Student is passing if he/she
scores marks equal to and above 40 in each course. If student scores aggregate greater than 75%,
then the grade is distinction. If aggregate is 60>= and <75 then the grade if first division. If
aggregate is 50>= and <60, then the grade is second division. If aggregate is 40>= and <50, then the
grade is third division
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.
Problem Statement:
Outcomes:
2. Students will be able to demonstrate different Operator & formulas for grade and sum.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more
Theory:
In this assignment user has to enter five different marks for five subjects. Next, it will find the Total,
average, and Percentage of those Five Subjects. For this, we are using the arithmetic operator to
perform arithmetic operations.
Problem Description
The program takes in the marks of 5 subjects and displays the grade.
1. Take in the marks of 5 subjects from the user and store it in different variables.
2. Find the average of the marks.
3. Use an else condition to decide the grade based on the average of the marks.
4. Exit.
Following flowchart will show basic idea about sum,average calculation in python , same logic we
can apply fow percentage calculation.
Here is source code of the Python Program to take in the marks of 5 subjects and display the grade.
The program output is also shown below.
Conclusion: Thus, we have performed how to calculate percentage and grade, average in python.
Title:
To check whether input number is Armstrong number or not. An Armstrong number is an integer
with three digits such that the sum of the cubes of its digits is equal to the number itself.
Ex. 371.
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.
Problem Statement:
2. Students will be able to demonstrate different integer number for identifying armstrong number.
3. Students will be able to demonstrate different Operations on any integer by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more
Theory:
To understand this example, you should have the knowledge of following python programming
concept with basic topics:
Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
abcd... = an + bn + cn + dn + ...
In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the number
itself. For example:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.
Here, we ask the user for a number and check if it is an Armstrong number.
We need to calculate the sum of cube of each digit. So, we initialize the sum to 0 and obtain each
digit number by using the modulus operator %. Remainder of a number when it is divide by 10 is
the last digit of that number. We take the cubes using exponent operator.
Finally, we compare the sum with the original number and conclude that it is Armstrong number if
they are equal.
Sample Example:
input_num = (input("Enter any number: "))
digit_len = len(str(input_num))try:
arm_num = 0
val = int(input_num)
while val > 0:
reminder = val % 10
arm_num += reminder ** digit_len
val //= 10if int(input_num) == arm_num:
print(input_num, 'is an ARMSTRONG number')
else:
print(input_num, 'is NOT an armstrong number')except ValueError:
print("That's not a valid number, Try Again !")
Conclusion:
Thus, we have studied and performed armstrong number concept in python successfully.
Title:
To accept the number and Compute a) square root of number, b) Square of number, c) Cube of
number d) check for prime, d) factorial of number e) prime factors
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.
Problem Statement:
Outcomes:
2. Students will be able to demonstrate different integer number for identifying number operations.
3. Students will be able to demonstrate different Operations on any integer by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more
Theory:
To understand this experiment, you should have the knowledge of following Python programming
topics:
Python Input, Output and Import
Python provides numerous built-in functions that are readily available to us at the Python prompt.
Some of the functions like input() and print() are widely used for standard input and output
operations respectively. Let us see the output section first.
Python Output Using print() function
We use the print() function to output data to the standard output device (screen).
We can also output data to a file, but this will be discussed later. An example use is given below.
print('This sentence is output to the screen')
# Output: This sentence is output to the screen
Python Numbers
Integers, floating point numbers and complex numbers falls under Python numbers category. They
are defined as int, float and complex class in Python.
We can use the type() function to know which class a variable or a value belongs to and the
isinstance() function to check if an object belongs to a particular class.
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
Python Operators
Operators are special symbols in Python that carry out arithmetic or logical computation. The value
that the operator operates on is called the operand.
For example:
>>> 2+35
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the
operation.
sqrt() function is an inbuilt function in Python programming language that returns the square root
of any number.
yntax:
math.sqrt(x)
Returns:
It returns the square root of the number passed in the parameter.
Example:
Square of a Number
In this article, we will show you, How to write a Python Program to Calculate Square of a Number
using Arithmetic Operators, and Functions with example.
allows the user to enter any numerical value. Next, it will finds the square of that number using
Arithmetic Operator.
Example:
# Python Program to Calculate Square of a Number
number = float(input(" Please Enter any numeric Value : "))
square = number * number
print("The Square of a Given Number {0} = {1}".format(number, square))
Cube of a Number
we will show you, How to write a Python Program to Calculate Cube of a Number using Arithmetic
Operators, and Functions with example.
Example:
# Python Program to Calculate Cube of a Number
number = float(input(" Please Enter any numeric Value : "))
cube = number * number * number
print("The Cube of a Given Number {0} = {1}".format(number, cube))
Input: n = 15
Output: false
Input: n = 1
Output: false
The idea to solve this problem is to iterate through all the numbers starting from 2 to (N/2) using a
for loop and for every number check if it divides N. If we find any number that divides, we return
false. If we did not find any number between 2 and N/2 which divides N then it means that N is
prime and we will return True.
Below is the Python program to check if a number is prime:
num = 11
# If given number is greater than 1
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, num//2):
The factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. Factorial is not defined for
negative numbers and the factorial of zero is one, 0! = 1.
factorial() in Python
Not many people know, but python offers a direct function that can compute the factorial of a
number without writing the whole code for computing factorial.
Naive method to compute factorial
# Python code to demonstrate naive method
# to compute factorial
n = 23
fact = 1
for i in range(1,n+1):
fact = fact * i
Using math.factorial()
This method is defined in “math” module of python. Because it has C type internal implementation,
it is fast.
math.factorial(x)
Parameters :
x : The number whose factorial has to be computed.
Return value :
Returns the factorial of desired number.
Exceptions :
Raises Value error if number is negative or non-integral.
Conclusion: Thus , in this experiment we have studied and performed mathematical operation on
given number.
Title:
To input binary number from user and convert it into decimal number.
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.
Problem Statement:
2. Students will be able to demonstrate different integer number for identifying number operations.
3. Students will be able to demonstrate different Operations on any integer by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more
Theory:
The number systems refer to the number of symbols or characters used to represent any numerical
value. The number system that you typically use every day is called decimal. In the decimal system,
you use ten different symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. With these ten symbols, you can
represent any quantity. Binary, hexadecimal, and octal refer to different number systems.
When you run out of symbols, you go to the next digit placement. In the decimal system, to
represent one higher than 9, you use 10 meaning one unit of ten and zero units of one. However, it
is different in other number systems. For example, when you consider a binary system which only
uses two symbols: 0 and 1, when you run out of symbols, you need to go to the next digit
placement. So this is how you will count in binary: 0, 1, 10, 11, 100, 101 and so on.
Let's check out some of the number systems in more detail in the next sections.
Furthermore, there are no more symbols left. You do not go to the digit 2 because 2 doesn't exist in
binary. Instead, you use a special combination of 1s and 0s. In a binary system, 1000 is equal to 8 in
decimal. In binary, you use powers of two, which means 8 is basically: (1(2^3)) + (0(2^2)) +
(0(2^1)) + (0(2^0))= 8. The position of the 1 and 0 defines the power to which 2 is to be raised to.
In Python, you can simply use the bin() function to convert from a decimal value to its
corresponding binary value.
And similarly, the int() function to convert a binary to its decimal value. The int() function
takes as second argument the base of the number to be converted, which is 2 in case of binary
numbers.
Convert Binary to Decimal in Python
To convert binary to decimal number in python, you have to ask from user to enter a number in
binary number system to convert that number into decimal number system as shown in the program
given here.
Approach:
The idea is to extract the digits of given binary number starting from right most digit and keep a
variable dec_value. At the time of extracting digits from the binary number, multiply the digit with
the proper base (Power of 2) and add it to the variable dec_value. At the end, the variable dec_value
will store the required decimal number.
Here is the sample run of the above Python program shows how to convert binary number to
decimal number:
for i in range(len(b_num)):
digit = b_num.pop()
if digit == '1':
value = value + pow(2, i)
print("The decimal value of the number is", value)
Conclusion: Thus in this experiment we have studied and performed number conversion in python
successfully.
Title:
To accept a number from user and print digits of number in a reverse order.
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.
Problem Statement:
1. Students will be able to understand basic concept of number reverse order logic.
2. Students will be able to demonstrate different integer number for identifying number operations.
3. Students will be able to demonstrate different Operations on any integer by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more
Theory:
In this assignment we are going to perform program to reverse a number in python allows the user
to enter any positive integer and then, that number is assigned to variable Number.
Next, Condition in the While loop will make sure that, the given number is greater than 0
From the above example, User Entered value: Number = 1456 and Reverse = 0
First Iteration
Reminder = Number %10
Reminder = 1456%10 = 6
Reverse = Reverse *10 + Reminder
Reverse = 0 * 10 + 6 = 0 + 6 = 6
Number = Number //10
Number = 1456 //10 = 145
From the Second Iteration of Python reverse a Number program, the values of both Number and
Reverse has been changed as: Number = 14 and Reverse = 65
Reminder = 14%10 = 4
Number = 1
Fourth Iteration
From the Second Iteration the values of both Number and Reverse has been changed as: Number =
1 and Reverse = 654
Reminder = 1 %10 = 1
Number = 0
Problem Solution
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print("Reverse of the number:",rev)
Program Explanation
Case 2:
Enter number: 4538
Reverse of the number: 8354
This program to reverse a number in python allows the user to enter any positive integer and then,
we are going to reverse a number using Python Functions
Conclusion: Thus in this experiment we have studied and performed reverse number conversion in
python successfully.
Title:
To accept list of N integers and partition list into two sub lists even and odd numbers.
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.
Problem Statement:
3. Students will be able to demonstrate different Operations on any integer by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more
Theory:
Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes.
There are various data types in Python. Some of the important types are listed below.
•Python Numbers
Integers, floating point numbers and complex numbers falls under Python numbers category. They
are defined as int, float and complex class in Python. We can use the type() function to know which
class a variable or a value belongs to and the isinstance() function to check if an object belongs to a
particular class.
>>>a = 5
>>>a = 2.0
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements.
Each element or value that is inside of a list is called an item. Just as strings are defined as
characters between quotes, lists are defined by having values between square brackets [ ].
Lists are great to use when you want to work with many related values. They enable you to keep
data together that belongs together, condense your code, and perform the same methods and
operations on multiple values at once.
When thinking about Python lists and other data structures that are types of collections, it is useful
to consider all the different collections you have on your computer: your assortment of files, your
song playlists, your browser bookmarks, your emails, the collection of videos you can access on a
streaming service, and more.
List is an ordered sequence of items. It is one of the most used datatype in Python and is very
flexible. All the items in a list do not need to be of the same type.
Declaring a list is pretty straight forward. Items separated by commas are enclosed within brackets
[ ].
We can use the slicing operator [ ] to extract an item or a range of itemsfrom a list.
Example
a = [5,10,15,20,25,30,35,40]
# a[2] = ?
# a[0:3] = ?
# a[5:] =
Example:
Example 1: count Even and Odd numbers from given list using for loop
Iterate each element in the list using for loop and check if num % 2 == 0, the condition to check
even numbers. If the condition satisfies, then increase even count else increase odd count.
Problem Solution
Case 2:
Enter number of elements:3
Enter element:23
Enter element:44
Program/Source Code
a=[]
Conclusion:
Thus, in this experiment we have studied and performed operations on list successfully.
Title:
Write a python program that accepts a string from user and perform following string operations- i.
Calculate length of string ii. String reversal iii. Equality check of two strings iii. Check palindrome
ii. Check substring
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.
Problem Statement:
3. Students will be able to demonstrate different Operations on any string by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more
Theory:
A string is a list of characters in order. A character is anything you can type on the keyboard in one
keystroke, like a letter, a number, or a backslash. Strings can have spaces: "hello world". An empty
string is a string that has 0 characters.
String Manipulation
Accessing
letter=word[0]
Length
>>> len(word)
11
Finding
Count
Keep in mind that python, as many other languages, starts to count from 0!!
Split Strings
Startswith / Endswith
>>> word.startswith("H")
True
>>> word.endswith("d")
True
>>> word.endswith("w")
False
Example: Let the input string be “i like this program very much”. The function should change the
string to “much very program this like i”
Input: hello
Output: olleh
The format() method that is available with the string object is very versatile and powerful in
formatting strings. Format strings contains curly braces {} as placeholders or replacement fields
which gets replaced.
We can use positional arguments or keyword arguments to specify the order.
The format() method can have optional format specifications. They are separated from field
name using colon. For example, we can left-justify <, right-justify > or center ^ a string in the given
space. We can also format integers as binary, hexadecimal etc. and floats can be rounded or
displayed in the exponent format. There are a ton of formatting you can use.
Conclusion:
Thus, in this experiment we have studied and performed string operation successfully.
Title:
To copy contents of one file to other. While copying a) all full stops are to be replaced with commas
b) lower case are to be replaced with upper case c) upper case are to be replaced with lower case.
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in
programming approach with the help of formulas and equations.
Problem Statement:
3. Students will be able to demonstrate different Operations on any igiven file by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard
Disk or more
Theory:
Python has several functions for creating, reading, updating, and deleting files.
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.
When we want to read from or write to a file we need to open it first. When we are done, it needs to
be closed, so that resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order.
1. Open a file
File Handling
The key function for working with files in Python is the open() function.
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
The code above is the same as:
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Python has a built-in function open() to open a file. This function returns a file object, also called
a handle, as it is used to read or modify the file accordingly.
>>> f = open("test.txt") # open file in current directory
We can specify the mode while opening a file. In mode, we specify whether we want to read 'r',
write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or
When we are done with operations to the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file and is done using Python close()
method.
Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to close
the file.
f = open("test.txt",encoding = 'utf-8')# perform file operationsf.close()
This method is not entirely safe. If an exception occurs when we are performing some operation
with the file, the code exits without closing the file.
A safer way is to use a try...finally block.
try: f = open("test.txt",encoding = 'utf-8') # perform file operationsfinally: f.close()
In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive
creation 'x' mode.
We need to be careful with the 'w' mode as it will overwrite into the file if it already exists. All
previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write() method. This
method returns the number of characters written to the file.
with open("test.txt",'w',encoding = 'utf-8') as f: f.write("my first file\n") f.write("This file\n\n")
f.write("contains three lines\n")
his program will create a new file named 'test.txt' if it does not exist. If it does exist, it is
overwritten.
We must include the newline characters ourselves to distinguish different lines.
How to read files in Python?
'This'
' is '
''
We can see that, the read() method returns newline as '\n'. Once the end of file is reached, we get
empty string on further reading.
We can change our current file cursor (position) using the seek() method. Similarly, the tell()
method returns our current position (in number of bytes).
>>> f.tell() # get the current file position
56
This file
We can read a file line-by-line using a for loop. This is both efficient and fast.
>>> for line in f:
This file
>>> f.readline()
'This file\n'
>>> f.readline()
>>> f.readline()
''
Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading
method return empty values when end of file (EOF) is reached.
>>> f.readlines()
Conclusion: