Python 1
Python 1
❖Python Introduction
➢ Python is a general purpose, dynamic, high level, and interpreted programming language. It
supports Object Oriented programming approach to develop applications. It is simple and easy
to learn and provides lots of high-level data structures.
➢ Python is easy to learn yet powerful and versatile scripting language, which makes it attractive
for Application Development. Python's syntax and dynamic typing with its interpreted nature
make it an ideal language for scripting and rapid application development.
➢ Python supports multiple programming pattern, including object-oriented, imperative, and
functional or procedural programming styles.
➢ Python is not intended to work in a particular area, such as web programming. That is why it is
known as multipurpose programming language because it can be used with web, enterprise, 3D
CAD, etc.
➢ We don't need to use data types to declare variable because it is dynamically typed so we can
write a=10 to assign an integer value in an integer variable.
➢ Python makes the development and debugging fast because there is no compilation step
included in Python development, and edit-test-debug cycle is very fast.
❖ Python History
➢ Python laid its foundation in the late 1980s.
➢ The implementation of Python was started in the December 1989 by Guido Van Rossum at
CWI in Netherland.
➢ In February 1991, van Rossum published the code (labeled version 0.9.0) to alt.sources.
➢ In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce.
➢ Python 2.0 added new features like: list comprehensions, garbage collection system.
➢ On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify
fundamental flaw of the language.
➢ ABC programming language is said to be the predecessor of Python language which was
capable of Exception Handling and interfacing with Amoeba Operating System.
➢ Python is influenced by following programming languages:
o ABC language.
o Modula-3
❖ Python Features
1) Easy to Learn and Use
Python is easy to learn and use. It is developer-friendly and high level programming language.
2) Expressive Language
Python language is more expressive means that it is more understandable and readable.
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time. This
makes debugging easy and thus suitable for beginners.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh etc. So,
we can say that Python is a portable language.
6) Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come into existence.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can be
used further in our python code.
Python has a large and broad library and prvides rich set of module and functions for
rapid application development.
10) Integrated
It can be easily integrated with languages like C, C++, JAVA etc.
➢ Let's run a python statement to print the traditional hello world on the console. Python3
provides print() function to print some message on the console. We can pass the
message as a string into this function. Consider the following image.
Here, we get the message "Hello World !" printed on the console.
Print ("hello world"); #here, we have used print() function to print the message on the console.
To run this file named as first.py, we need to run the following command on the terminal.
$ python3 first.py
Hence, we get our output as the message Hello World ! is printed on the console.
❖ Python Variables
➢ Variable is a name which is used to refer memory location. Variable also known as identifier
and used to hold value.
➢ In Python, we don't need to specify the type of variable because Python is a type infer
language and smart enough to get variable type.
➢ Variable names can be a group of both letters and digits, but they have to begin with a
letter or an underscore.
➢ It is recomended to use lowercase letters for variable name. Rahul and rahul both are two
different variables.
Eg:
Syntax :input(prompt)
Example:
❖ Python Comments
➢ Comments in Python can be used to explain any program code. It can also be used to hide the
code as well.
➢ Comments are the most helpful stuff of any program. It enables us to understand the way, a
program works. In python, any statement written along with # symbol is known as a comment.
The interpreter does not interpret the comment.
➢ Comment is not a part of the program, but it enhances the interactivity of the program and
makes the program readable.
➢ Python supports two types of comments:
1) Single Line Comment:In case user wants to specify a single line comment, then comment
must start with ?#?
Eg:
# This is single line comment.
print "Hello Python"
Output:
Hello Python
A=10
b="Hi Python"
c = 10.5
print(type(a));
print(type(b));
print(type(c));
Output:
<type 'int'>
<type 'str'>
<type 'float'>
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
1. Numbers
➢ Number stores numeric values. Python creates Number objects when a number is assigned
to a variable. For example;
➢ a = 3 , b = 5 #a and b are number objects
➢ Python allows us to use a lower-case L to be used with long integers. However, we must
always use an upper-case L to avoid confusion.
➢ A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and
imaginary parts respectively).
2. String
➢ The string can be defined as the sequence of characters represented in the quotation marks.
In python, we can use single, double, or triple quotes to define a string.
➢ String handling in python is a straightforward task since there are various inbuilt
functions and operators provided.
➢ In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
➢ The operator * is known as repetition operator as the operation "Python " *2 returns
"Python Python ".
➢ The following example illustrates the string handling in python.
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
➢ As shown in python, the slice operator [] is used to access the individual characters of the string.
However, we can use the : (colon) operator in python to access the substring. Consider the following
example.
➢ Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str =
'python' is given, then str[1:3] will always include str[1] = 'p', str[2] = 'y', str[3] = 't' and nothing else.
✓ String Operators
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the
operator.
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[:] It is known as range slice operator. It is used to access the characters from the specified
range.
not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we need to
prithe actual meaning of escape characters such as "C://python". To define any string as
a raw string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers used in C
programming like %d or %f to map their values in python. We will discuss how
formatting is done in python.
Example
Consider the following example to understand the real use of Python operators.
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str print('wo'
not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Integer = 10;
Float = 1.290
String = "Ayush"
print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string
... My value is %s"%(Integer,Float,String));
PREPARED BY: DHABALIYA NIKITA 10
UNIT-1 INTRODUCTION TO PYTHON BCA-2019
Output:
Method Description
center(width ,fillchar) It returns a space padded string with the original string
centred with equal number of left and right spaces.
decode(encoding = 'UTF8', Decodes the string using codec registered for encoding.
errors = 'strict')
find(substring ,beginIndex, It returns the index value of the string where substring is
endIndex) found between begin index and end index.
isalpha() It returns true if all the characters are alphabets and there is
at least one character, otherwise False.
isdecimal() It returns true if all the characters of the string are decimals.
isdigit() It returns true if all the characters are digits and there is at
least one character, otherwise False.
rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string from the
backward direction. It returns the list of words in the string. If
Separator is not specified then the string splits according to
the white-space.
split(str,num=string.count(str)) Splits the string according to the delimiter str. The string splits
according to the space if the delimiter is not provided. It
returns the list of substring concatenated with the delimiter.
splitlines(num=string.count('\n') It returns the list of strings at each line with newline removed.
)
startswith(str,beg=0,end=len(st It returns a Boolean value if the string starts with given str
r)) between begin and end.
title() It is used to convert the string into the title-case i.e., The
string meEruT will be converted to Meerut.
3. List
➢ Lists are similar to arrays in C. However; the list can contain data of different types. The items
stored in the list are separated with a comma (,) and enclosed within square brackets [].
➢ We can use slice [:] operators to access the data of the list. The concatenation operator (+)
and repetition operator (*) works with the list in the same way as they were working with the
strings.
➢ Consider the following example.
l = [1, "hi", "python",
2] print (l[3:]);
print (l[0:2]);
print (l);
print (l + l);
print (l * 3);
Output:
[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
✓ Iterating a List
➢ A list can be iterated by using a for - in loop. A simple list containing four strings can
be iterated as follows.
Output:
John
David
James
Jonathan
SN Function Description
SN Function Description
1 list.append(obj) The element represented by the object obj is added to the list.
4 list.count(obj) It returns the number of occurrences of the specified object in the list.
5 list.extend(seq) The sequence represented by the object seq is extended to the list.
6 list.index(obj) It returns the lowest index in the list that object appears.
7 list.insert(index, obj) The object is inserted into the list at the specified index.
11 list.sort([func]) It sorts the list by using the specified compare function if given.
PREPARED BY: DHABALIYA NIKITA 15
UNIT-1 INTRODUCTION TO PYTHON BCA-2019
4. Tuple
➢ Python Tuple is used to store the sequence of immutable python objects. Tuple is similar to lists
since the value of the items stored in the list can be changed whereas the tuple is immutable
and the value of the items stored in the tuple can not be changed.
➢ A tuple can be written as the collection of comma-separated values enclosed with the small
brackets. A tuple can be defined as follows.
Example
Output:
Output:
Consider the following image to understand the indexing and slicing in detail.
SN Function Description
1 cmp(tuple1, tuple2) It compares two tuples and returns true if tuple1 is greater
than tuple2 otherwise false.
List VS Tuple
List Tuple
The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().
The List has the variable length. The tuple has the fixed length.
PREPARED BY: DHABALIYA NIKITA 17
UNIT-1 INTRODUCTION TO PYTHON BCA-2019
The list provides more functionality than The tuple provides less functionality than the list.
tuple.
The list Is used in the scenario in which we The tuple is used in the cases where we need to
need to store the simple collections with no store the read-only collections i.e., the value of
constraints where the value of the items the items can not be changed. It can be used as
can be changed. the key inside the dictionary.
5. Python Dictionary
➢ Dictionary is used to implement the key-value pair in python. The dictionary is the data type in
python which can simulate the real-life data arrangement where some specific value exists for
some particular key.
➢ In other words, we can say that a dictionary is the collection of key-value pairs where the value
can be any python object whereas the keys are the immutable python object, i.e., Numbers,
string or tuple.
➢ Dictionary simulates Java hash-map in python.
In the above dictionary Dict, The keys Name, and Age are the string that is an immutable object.
Output
<class 'dict'>
printing Employee data ....
{'Age': 29, 'salary': 25000, 'Name': 'John', 'Company': 'GOOGLE'}
Output:
<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE
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.
✓ Iterating Dictionary
A dictionary can be iterated using the for loop as given below.
Example 1
# for loop to print all the keys of a dictionary
Output:
Name
Company
salary
Age
Output:
Salary 25000
Company GOOGLE
Name Johnn
Age 29
SN Function Description
1 cmp(dict1, dict2) It compares the items of both the dictionary and returns true if
the first dictionary values are greater than the second dictionary,
otherwise it returns false.
Method Description
dict.fromkeys(iterable, value = Create a new dictionary from the iterable with the values
None, /) equal to value.
dict.get(key, default = "None") It is used to get the value specified for the passed key.
dict.setdefault(key,default= It is used to set the key to the default value if the key is not
"None") specified in the dictionary
index()
Get index of specifying element in dictionary
1. if statement
➢ The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical expression
which can be either evaluated to true or false.
syntax:
if expression:
statement
Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
Output:
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
2. if-else statement
➢ The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.
➢ If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
Syntax:
if condition:
#block of statements
else:
#another block of statements (else-block)
Output:
3. elif statement
➢ The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional.
➢ The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement
Syntax:
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");
Output:
Example 2
marks = int(input("Enter the marks? "))
if marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you are fail ?")
❖ Python Loops
➢ The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program. The execution of a specific code may
need to be repeated several numbers of times.
➢ For this purpose, The programming languages provide various types of loops which are
capable of repeating some specific code several numbers of times.
1. for loop
The for loop in Python is used to iterate the statements or a part of the program several times. It
is frequently used to traverse the data structures like list, tuple, or dictionary.
Example
i=1
n=int(input("Enter the number up to which you want to print the natural numbers?"))
for i in range(0,10):
print(i,end = ' ')
Output:
0123456789
✓ Python for loop example : printing the table of the given number
i=1;
num = int(input("Enter a number:"));
for i in range(1,11):
print("%d X %d = %d"%(num,i,num*i));
Output:
Enter a number:10
10X1=10
10X2=20
10X3=30
10X4=40
10X5=50
10X6=60
10X7=70
10X8=80
10X9=90
10X10=100
Example 1
Output:
***
****
*****
2. while loop
➢ The while loop is also known as a pre-tested loop. In general, a while loop allows a part of the
code to be executed as long as the given condition is true.
➢ It can be viewed as a repeating if statement. The while loop is mostly used in the case where
the number of iterations is not known in advance.
while expression:
statements
➢ Here, the statements can be a single statement or the group of statements. The expression
should be any valid python expression resulting into true or false. The true is any non-zero
value.
Example 1
i=1;
while i<=10:
print(i);
i=i+1;
Output:
12345678910
❖ Python Functions
➢ Functions are the most important aspect of an application. A function can be defined as the
organized block of reusable code which can be called whenever required.
➢ Python allows us to divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the python program.
➢ In other words, we can say that the collection of functions creates a program. The function is
also known as procedure or subroutine in other programming languages.
➢ Python provide us various inbuilt functions like range() or print(). Although, the user can create
its functions which can be called user-defined functions.
Creating a function
➢ In python, we can use def keyword to define the function. The syntax to define a function
in python is given below.
def my_function():
function-suite
return <expression>
➢ The function block is started with the colon (:) and all the same level block statements remain
at the same indentation.
➢ A function can accept any number of parameters that must be the same in the definition and
function calling.
Function calling
➢ In python, a function must be defined before the function calling otherwise the python interpreter
gives an error. Once the function is defined, we can call it from another function or the python
prompt. To call the function, use the function name followed by the parentheses.
➢ A simple function that prints the message "Hello Word" is given below.
def hello_world():
print("hello world")
hello_world()
Output:
hello world
Parameters in function
The information into the functions can be passed as the parameters. The parameters are specified
in the parentheses. We can give any number of parameters, but we have to separate them with a
comma.
Consider the following example which contains a function that accepts a string as the
parameter and prints it.
Example 1
Example 2
Output:
Enter a: 10
Enter b: 20
Sum = 30
Output:
Output:
❖Types of arguments
➢ There may be several types of arguments which can be passed at the time of function calling.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1. Required Arguments
➢ Till now, we have learned about function calling in python. However, we can provide the
arguments at the time of function calling. As far as the required arguments are concerned, these
are the arguments which are required to be passed at the time of function calling with the exact
match of their positions in the function call and function definition. If either of the arguments is
not provided in the function call, or the position of the arguments is changed, then the python
interpreter will show the error.
Example 1
Output:
Example2
the function simple_interest accepts three arguments and returns the simple interest accordingly
def simple_interest(p,t,r):
return (p*t*r)/100
p = float(input("Enter the principle amount? "))
r = float(input("Enter the rate of interest? "))
t = float(input("Enter the time in years? "))
print("Simple Interest: ",simple_interest(p,r,t))
Output:
2. Keyword arguments
➢ Python allows us to call the function with the keyword arguments. This kind of function call will
enable us to pass the arguments in the random order.
➢ The name of the arguments is treated as the keywords and matched in the function calling and
definition. If the same match is found, the values of the arguments are copied in the function
definition.
Example 1
#function func is called with the name and message as the keyword
arguments def func(name,message):
print("printing
the message with",name,"and ",message)
func(name = "John",message="hello") #name and message is copied with the values John and
h ello respectively
Output:
3. Default Arguments
➢ Python allows us to initialize the arguments at the function definition. If the value of any of the
argument is not provided at the time of function call, then that argument can be initialized with
the value given in the definition even if the argument is not specified at the function call.
Example 1
def printme(name,age=22):
print("My
name is",name,"and age is",age)
printme(name = "john") #the variable age is not passed into the function however the default
val ue of age is considered in the function
Output:
Example 2
def printme(name,age=22):
print("My
name is",name,"and age is",age)
printme(name = "john") #the variable age is not passed into the function however the default val
ue of age is considered in the function
printme(age = 10,name="David") #the value of age is overwritten here, 10 will be printed as age
Output:
Example
def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
Output:
David
smith
nick
❖Scope of variables
➢ The scopes of the variables depend upon the location where the variable is being declared.
The variable declared in one part of the program may not be accessible to the other parts.
➢ In python, the variables are defined with the two types of scopes.
1. Global variables
2. Local variables
➢ The variable defined outside any function is known to have a global scope whereas the
variable defined inside a function is known to have a local scope.
Example 1
def print_message():
message = "hello !! I am going to print a message." # the variable message is local to the functi
on itself
print(message)
print_message()
print(message) # this will cause an error since a local variable cannot be accessible here.
Output:
hello !! I am going to print a message.
File "/root/PycharmProjects/PythonTest/Test1.py", line 5,
in print(message)
NameError: name 'message' is not defined
Example 2
def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
sum=0
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed
Output:
The sum is 60
Value of sum outside the function: 0
❖ Recursion in python
➢ A function that calls itself is a recursive function. This method is used when a certain problem is
defined in terms of itself. Although this involves iteration, using an iterative approach to solve
such a problem can be tedious. The recursive approach provides a very concise solution to a
seemingly complex problem. It looks glamorous but can be difficult to comprehend!
➢ The most popular example of recursion is the calculation of the factorial. Mathematically the
factorial is defined as: n! = n * (n-1)!
➢ We use the factorial itself to define the factorial. Hence, this is a suitable case to write a
recursive function. Let us expand the above definition for the calculation of the factorial value of
5.
5!=5X4!
5X4X3!
5X4X3X2!
5X4X3X 2X1!
5X4X3X 2X1
= 120
➢ While we can perform this calculation using a loop, its recursive function involves successively
calling it by decrementing the number until it reaches 1. The following is a recursive function to
calculate the factorial.
def factorial(n):
if n == 1:
print(n)
return 1
else:
print (n,'*', end=' ')
return n * factorial(n-1)
>>> factorial(5)
5*4*3*2*1
120
➢ When the factorial function is called with 5 as argument, successive calls to the same function
are placed, while reducing the value of 5. Functions start returning to their earlier call after the
argument reaches 1. The return value of the first call is a cumulative product of the return values
of all calls.
❖ Python Modules
➢ A python module can be defined as a python program file which contains a python code including
python functions, class, or variables. In other words, we can say that our python code file saved
with the extension (.py) is treated as the module. We may have a runnable code inside the python
module.
➢ Modules in Python provides us the flexibility to organize the code in a logical way.
➢ To use the functionality of one module into another, we must have to import the specific
module.
Example
In this example, we will create a module named as file.py which contains a function func
that contains a code to print some message on the console.
Here, we need to include this module into our main module to call the method displayMsg() defined
in the module named file.
➢ Hence, if we need to call the function displayMsg() defined in the file file.py, we have
to import that file as a module into our module as shown in the example below.
Example:
import file;
name = input("Enter the name?")
file.displayMsg(name)
Output:
Enter the name?John
Hi John
Consider the following module named as calculation which contains three functions as
summation, multiplication, and divide.
calculation.py:
Main.py:
Output:
3. Opening a file
➢ Python provides the open() function which accepts two arguments, file name and access mode
in which the file is accessed. The function returns a file object which can be used to perform
various operations like reading, writing, etc.
➢ The files can be accessed using various modes like read, write, or append. The following
are the details about the access mode to open a file.
Access Description
mode
R It opens the file to read-only. The file pointer exists at the beginning. The file is by
default open in this mode if no access mode is passed.
Rb It opens the file to read only in binary format. The file pointer exists at the beginning
of the file.
r+ It opens the file to read and write both. The file pointer exists at the beginning of the
file.
rb+ It opens the file to read and write both in binary format. The file pointer exists at the
beginning of the file.
W It opens the file to write only. It overwrites the file if previously exists or creates a
new one if no file exists with the same name. The file pointer exists at the beginning
of the file.
Wb It opens the file to write only in binary format. It overwrites the file if it exists
previously or creates a new one if no file exists with the same name. The file pointer
exists at the beginning of the file.
w+ It opens the file to write and read both. It is different from r+ in the sense that it
overwrites the previous file if one exists whereas r+ doesn't overwrite the previously
written file. It creates a new file if no file exists. The file pointer exists at the
beginning of the file.
wb+ It opens the file to write and read both in binary format. The file pointer exists at the
beginning of the file.
A It opens the file in the append mode. The file pointer exists at the end of the
previously written file if exists any. It creates a new file if no file exists with the
same name.
Ab It opens the file in the append mode in binary format. The pointer exists at the end
of the previously written file. It creates a new file in binary format if no file exists
with the same name.
a+ It opens a file to append and read both. The file pointer remains at the end of the file
if a file exists. It creates a new file if no file exists with the same name.
ab+ It opens a file to append and read both in binary format. The file pointer remains at
the end of the file.
Let's look at the simple example to open a file named "file.txt" (stored in the same directory) in read
mode and printing its content on the console.
Example
#opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
Output:
<class '_io.TextIOWrapper'>
file is opened successfully
SYNTAX:fileobject.close()
Example
# opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
fileobj.read(<count>)
Here, the count is the number of bytes to be read from the file starting from the beginning of the file.
If the count is not specified, then it may read the content of the file until the end.
Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");
Output:
<class 'str'>
Hi, I am
Consider the following example which contains a function readline() that reads the first line of our
file "file.txt" containing three lines.
Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");
Output:
<class 'str'>
Hi, I am the file and being used as
Example
fileptr = open("file.txt","r");
for i in fileptr:
print(i) # i contains each line of the file
Output:
a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if
no file exists.
w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.
Example 1
#open the file.txt in append mode. Creates a new file if no such file exists.
fileptr = open("file.txt","a");
File.txt:
Example 2
#open the file.txt in write mode.
fileptr = open("file.txt","w");
Now, we can check that all the previously written content of the file is overwritten with the new text
we have passed.
File.txt:
a: It creates a new file with the specified name if no such file exists. It appends the content to the file if
the file already exists with the specified name.
w: It creates a new file with the specified name if no such file exists. It overwrites the existing
Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","x");
print(fileptr)
if fileptr:
print("File created successfully");
Output:
Example
# open the file file2.txt in read
mode fileptr = open("file2.txt","r")
#after the read operation file pointer modifies. tell() returns the location of the
file ptr.
Output:
For this purpose, the python provides us the seek() method which enables us to modify the file
pointer position externally.
1. <file-ptr>.seek(offset[, from)
offset: It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be moved. If it is set to 0, the
beginning of the file is used as the reference position. If it is set to 1, the current position of the file
pointer is used as the reference position. If it is set to 2, the end of the file pointer is used as the
reference position.
Example
# open the file file2.txt in read
mode fileptr = open("file2.txt","r")
Output:
❖Python os module
The os module provides us the functions that are involved in file processing operations like
renaming, deleting, etc.
rename(?current-name?, ?new-name?)
Example
import os;
remove(?file-name?)
Example
import os;