Module2 Python Programming
Module2 Python Programming
Module II: Functions- Definition, calling, arguments, anonymous function, recursion, return;
Modules & Packages - Built-in Modules, Creating Modules, import statement, Locating, modules
,Namespaces and Scope, dir (), reload (), Packages in Python; File Handling- open, close, write,
read, methods, rename, delete, directories;
Functions in Python
A group of related statements to perform a specific task is known as a function. Functions helpto
break the program into smaller units. Functions avoid repetition and enhance code reusability.
Functions provide better modularity in programming.
Python provides two types of functions
built in function
User defined function
Functions like input(), print() etc..are examples of built in functions. Code of these functions are
already defined. We can create our own functions to perform a particular task. These functions are
called user defined functions.
FUNCTION DEFINITION
Function block or function header begins with a keyword def followed by the
function name and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. Wecan also
define parameters inside these parentheses.
The first string after the function header is called the doc string and is short for
documentation string. It is used to explain in brief, what a function does. Althoughoptional,
documentation is a good programming practice.
The code block within every function starts with a colon ( : ) and is indented.
The return statement [ expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as returnNone.
SYNTAX
def functionname( parameters ):
“ function_docstring”
Function_suite
Return [ expression ]
EXAMPLE PROGRAM
def sum_of_two_numbers(a,b):
sum = a + b
Return sum
FUNCTION CALLING
After defining a function, we can call the function from another function or directly from python
prompt. The order of the parameters specified in the function definition should be preserved in
function call also.
EXAMPLE PROGRAM
a= int(input(“enter the first number:”))
b=int(input(“enter the second number:”))
s=sum_of_two_numbers(a,b)
print(“sum of"a,”and”,b,”is",s)
1
Output
Enter the first number:4
Enter the second number:3
Sum of 4 and 3 is 7
All the parameters in Python are passed by reference. It means if we change a parameter which
refers to within a function, the change also reflects back in the calling function.
Parameters and variables defined inside a function is not visible from outside. Hence, they have a
local scope. Lifetime of a variable is the period throughout which the variable exists in the memory.
The lifetime of variables inside a function is as long as the function executes. All variables in a
program may not be accessible at all locations in that program. This depends on where we have
declared a variable. The scope of a variable determines the portion of the program where we can
access a particular identifier. They are destroyed once we return from the function. Hence, a
function does not remember the value of a variablefrom its previous calls.
EXAMPLE PROGRAM
def value_change (a) : #Function Header
a=10
Print (value inside function=" ,a) #prints the value of a inside function return
#Main Program Code
a =int (input ( "Enter a number: ")
value_change (a) #Function calling
print ( "Value outside function=", a) #prints value or a outside function
output
enter a number: 3
value inside function:10
value outside function:3
Here in the main program a number is read and stored in variable a. Even though this value is
passed to the function value_change, a is assigned another value inside the function. This value is
displayed inside the function. after returning from the function, it will display the value read from
the function. the variable a declared inside function value_change is local that function and hence
after returning to the main program, a will display the value stored in the main program.
FUNCTION ARGUMENTS
REQUIRED ARGUMENTS
Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition.
EXAMPLE PROGRAM
2
a=10
return
OUTPUT
Enter a number:4
Note
The above example contains a function which requires 1 parameter. In the main programcode, the
function is called without passing the parameter. Hence it resulted in the error.
KEYWORD ARGUMENTS
When we use keyword arguments in a function call, the caller identifies the arguments by the
parameter name. This allows us to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters.
EXAMPLE PROGRAM
#Function definition
def studentinfo(rollno, name, course="UG") :
“This prints a passed info into this function"
print ("Roll Number: ", rollno)
print ("Name: ", name)
print ("Course: ", course)
#Function calling
3
studentinfo(rollno= 51, name="Tom”)
OUTPUT
Roll Number: 50
Name: Jack
Course: UG
Roll Number: 51
Name: Tom
Course: UG
DEFAULT ARGUMENTS
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument. The following example shows how default arguments areinvoked.
EXAMPLE PROGRAM
#Function definition
def studentinfo(rollno, name, course="UG") :
“This prints a passed info into this function"
print ("Roll Number: ", rollno)
print ("Name: ", name)
print ("Course: ", course)
#Function calling
OUTPUT
Roll Number: 50
Name: Jack
Course: UG
Roll Number: 51
Name: Tom
Course: UG
In some cases we may need to process a function for more arguments than specified while
defining the function. These arguments are called variable-length arguments and are not named
4
in the function definition, unlike required and default arguments. An asterisk (*) is placed before
the variable name that holds the values of all non-keyword variable arguments. This tuple
remains empty if no additional arguments are specified during the function call.
SYNTAX
"function_docstring"
function_statements
return [expression]
EXAMPLE PROGRAM
#Function definition
def variablelengthfunction(*argument) :
OUTPUT
In Python, anonymous function is a function that is defined without a name. While normal
functions are defined using the def keyword, in Python anonymous functions are defined using the
lambda keyword. Hence, anonymous functions are also called lambda functions.
CHARACTERISTICS
⚫ Lambda functions can take any number of arguments but return only one value in the
form of an expression.
⚫ Lambda functions have their own local namespace and cannot access variables other
than those in their parameter list and those in the global namespace.
SYNTAX
EXAMPLE PROGRAM
OUTPUT
Enter a number: 5
Square of 5 is 25
In the above example, lambda is the keyword, x shows the argument passed, and x*x is the
expression to be evaluated and stored in the variable square. In the case of calculating the square
of a number, only one argument is passed. More than one argument is possible for lambda
functions.
EXAMPLE PROGRAM
OUTPUT
⚫ We use lambda functions when we require a nameless function for a short period oftime. In
python, we generally use it as an argument to a higher-order function (a function that takes
in other functions as arguments).
⚫ Lambda functions are used along with built-in functions like filter(), map) etc.
6
EXAMPLE PROGRAM WITH MAP()
⚫ The function is called with all the items in the list and a new list is returned which contains
items returned by that function for each item.
CODE
OUTPUT
FILTER( ) FUNCTION
⚫ The function filter(function, list) offers an elegant way to filter out all the elements of a list,
for which the function returns True.
⚫ func returns a Boolean value, ie. either True or False applied to every element of thelist lis.
⚫ Only if func returns True will the element of the list be included in the result list.
⚫ The function is called with all the items in the list and a new list is returned whichcontains
items for which the function evaluates to True.
CODE
#Lambda Function to filter out only the odd numbers from a list
oldlist= [2,31, 42,11,6,5,23,44]
# Usage of lambda funct ion
newlist=list (filter (lambda x:(x*2 ! =0),oldlist) )
print (oldlist)
print (newlist)
7
OUTPUT
REDUCE( ) FUNCTION
⚫ The function reduce(func, seg) continually applies the function func() to the sequence
seq.
This is a really useful function for performing some computation on a list and
returning the result.
import functools
list= [1,2,3,4]
product=functools . reduce (lambda x, Y: x * Y, list)print
(list)
print ("Product=", product)
OUTPUT
[1, 2, 3, 4]
Product= 24
RECURSIVE FUNCTIONS
⚫ A function can call other functions. It is possible for a function to call itself. This is
known as recursion.
Example Program
OUTPUT
Enter a number: 5
The factorial of 5 is 120
EXPLANATION
When we call this function with a positive integer, it will recursively call itself by
decreasing the number.
Each function call multiplies the number with the factorial of number-1 until thenumber is
equal to one.
This recursive call can be explained in the following steps. Our recursion ends when the
number reduces to 1. This is called the base condition.
Every recursive function must have a base condition that stops the recursion or elsethe
function calls itself infinitely.
⚫ Python has a strong mechanism of returning more than one value at a time. This isvery
flexible when the function needs to return more than one value.
⚫ Instead of writing separate functions for returning individual values, we can return allthe
values within same function.
Example Program
OUTPUT
ILLUSTRATIVE PROGRAMS
CODE
OUTPUT
Enter a number: 5
Square of 5 is 25
CODE
def gcd(a,b):
10
for i in range(1,min(a , b)+1):
gcd=i
print(gcd)
gcd(a,b)
OUTPUT
CODE
lis1=list(map(int,lis.split()))
sum=0
for i in lis1:sum+=i
OUTPUT
import math
power = math.pow(base_number,exponent)
print("Power is =",power)
11
OUTPUT
Power is = 16.0
OR
print("Result is =",power)
OUTPUT
Result is = 32
CODE
def selection_sort(alist):
smallest = i
smallest = j
alist[i], alist[smallest] =alist[smallest], alist[i]
selection_sort(alist)
12
OUTPUT
CODE
def insertion_sort(alist):
for i in range(1, len(alist)):
temp = alist[i]
j=i-1
alist[j + 1] = alist[j]
j=j-1
alist[j + 1] = temp
insertion_sort(alist)
print(alist)
OUTPUT
CODE
def bubble_sort(alist):
no_swap = True
if no_swap:
return
bubble_sort(alist)
print(alist)
OUTPUT
for i in range(len(alist)):
if alist[i] == key:
return i
return -1
alist = alist.split()
if index < 0:
else:
def selection_sort(alist):
smallest = i
smallest = j
start = 0
end = len(alist)
end = mid
start = mid + 1
else:
return mid
15
return -1
alist = alist.split()
selection_sort(alist)
print(alist)
if index < 0:
else:
OUTPUT
Modules Introduction
Modules refer to a file containing Python statements and definitions. A module is a Python
object with arbitrarily named attributes that we can bind and reference. We use modules to break
down large programs into small manageable and organized files. Further, modules provide
reusability of code. A module can define functions, classes and variables. A module can also
include runnable code. Python has a lot of standard modules (built-in modules) available. A full list
16
of Python standard modules is available in the Lib directory inside the location where you installed
Python.
CREATING MODULES
We can define our most used functions in a module and import it, instead of copying their
definitions into different programs. A file containing Python code, for e.g.: prime.py, is called a
module and its module name would be prime. The Python code for a module named test normally
resides in a file named test.py.
Let us create a module for finding the sum of two numbers. The following code creates a module in
Python. Type the code and save it as test.py.
Example
#Python Module example “””This
program adds two numbers and
return the result"""
Here we have a function sum() inside a module named test. The function takes in two
numbers and returns their sum.
IMPORT STATEMENT
We can use any Python source file as a module by executing an import statement in some other
Python source file. User-defined modules can be imported the same way as we import built-in
modules.
We use the import keyword to do this. The import has the following syntax.
When the interpreter encounters an import statement, it imports the module if the module is present
in the search path. A search path is a list of directories that the interpreter searches before importing
a module. For example, to import the module test.py, you need to put the following command at the
top of the script.
Example
import test
print (test.sum (2,3))
17
Output
When the above code in the example is executed, we get the result 5.
A module is loaded only once, regardless of the number of times it is imported. This preventsthe
module execution from happening over and over again if multiple imports occur.
We can import built-in or user-defined modules with an alias name. The following code shows how
the built-in module math can be imported using an alias name.
Example Program
import math as m
print ("The value of pi is", m.pi)
Output
We have renamed the math module as m. This can save typing time in some cases. It is important to
note that the name math is not recognized in our scope. Hence, math.pi is invalid, m.pi is the correct
implementation.
from...import statement
We can import specific names from a module without importing the module as a whole. The module
math contains a lot of built-in functions. But if we want to import only the pi function, the
from...import statement can be used. The following example illustrates importing pi from math
module.
Example Program
from math import pi
print ("The value of pi is:", pi)
Output
The value of pi is: 3.14159265359
We have imported only the pi function from the math module. Hence no need to use the dot
operator as given in the previous example. We can also import multiple attributes from the module
using from..import statement. The following example illustrates the import of pi as well as sqr( )
from the math module using from.. import statement.
Example Program
from math import pi, sqrt print
("The value of pi is", pi)
18
print (“The square root of 4 is: ", sqrt (4))
Output
The value of pi is: 3.14159265359The
square root of 4 is: 2.0
We can import all names(definitions) from a module using the following construct. The following
example shows how all the definitions from the math module can be imported.This makes all names
except those beginning with an underscore, visible in our scope.
Example Program
from math import *
print (The value of pi is:", pi)
print(“The square root of 4 is: ", sqrt (4))
Output
Here all functions in the module math are imported. But we have used ability only pi and sqrt.
Importing everything with the asterisk (*) symbol is not a good programming practice. This can
lead to duplicate definitions for an identifier. It also reduces the readability of our code.
LOCATING MODULES
When we import a module, the Python interpreter searches for the module in the following
sequence.
2. If the module isn't found, Python then searches each directory in the shell variable
PYTHONPATH.
3. If the above two mentioned fails, Python checks the default path. On UNIX, default path is
normally /usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable. The
sys.path variable contains the current directory, PYTHONPATH, and the installation dependent
default.
PYTHONPATH variable
set PYTHONPATH=/usr/1ocal/1ib/python
Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable
names (keys) and their corresponding objects (values). A Python statement can access variables in
a local namespace and in the global namespace. If a local and a global variable have the same
name, the local variable shadows the global variable.
Each function has its own local namespace. Python makes certain guesses on whether variables are
local or global. It assumes that any variable assigned a value in a function is local. Therefore, in
order to assign a value to a global variable within a function, you must first use the global
statement. The statement global variable_name tells Python variable_name is a global variable.
Once a variable is declared global, Python stops searching the local namespace for that
variable. Consider the following example.
Example Program
def Add ( ):
a= a + l
print (a)
Output
Traceback (most recent call last):
File "main.py" line 5, in <modules>Add(
)
File "main.py"1ine 3, in Adda=a +
l
UnboundLocalError: Local variable „a‟ referenced before assignment
When we run the above program, the output is listed above with errors. The reason is that weare trying
to add 1 to a before a is assigned a value. This is because even though a is assigned a value 10, its scope
is outside the function Add( ). Further Python always searches for variables in the local namespace.
20
Since a is not assigned value inside the function, it resulted in an error. The below program is re-
written using global variable concept.
Example Program
#Program to illustrate local and global namespacea=10
print a
def Add ( ) :
global a
a=20
a=a + l
print (a)
Add ( )
print (a)
Output10
21
21
In the above example, a is assigned a value 10 and it is printed. Inside the function, a is declared
global and it is incremented by one. The result is 21. Even after, exiting the function,when we try to
print the value of a, it is printing it as 21 since a is declared a global variable.
The dir( ) built-in function returns a sorted list of strings containing the names defined by amodule.
The list contains the names of all the modules, variables and functions that are defined in a module.
The following example illustrates the use of dir( ) function for the built-in module called math.
Example Program
Output
In the above output, _doc_ is present in every namespace. Initially it will be None, we can store
documentation here. file_ _ is the filename from which the module was loaded. name is the
name of the current module (minus the py extension). In the top-level script or in conversational
mode, this name is set to the string „ main ‟. The modules package attribute should be set.
Its value must be a string, but it can be the same value as its name . If the attribute is set to None
21
or is missing, the import system will fill it in with a more appropriate value. When the module is a
package, its package value should be set to its name . When the module is not a
package, package should be set to the empty string for top-level modules, or for submodules, to
the parent package's name. The restshows the built-in functions available in the math module.
Another example illustrates the use of dir() function along with user-defined modules.
Example Program
Output
[ „ builtins ‟ ,‟ doc ‟,‟ file ‟,‟ name ‟,‟ package ‟,‟ Sum ']
The output contains built-in strings and we have defined only one function called sum in that
module. _builtins_ contain Python's built-in error handling .
When the module is imported into a script, the code in the top-level portion of a module is
executed only once. Therefore, if you want to reexecute the top-level code in a module, you can
use the reload() function. The reload() function imports a previously imported module
again. The syntax of the reload() function is as follows.
reload ( module_name)
Here, module_name is the name of the module we want to reload and not the string containing the
module name. For example, to reload test module, do the following:
reload (test)
PACKAGES IN PYTHON
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and subpackages and so on. As our application program
grows larger in size with a lot of modules, we place similar modules in one package and
in different packages. This makes a project (program) easy to manage and different modules
conceptually clear. Similar, as a directory can contain sub-directories and files, a Python can
have sub-packages and modules. A directory must contain a file named init .py in order for
Python to consider it as a package. This file can be left empty but we generally place the
initialization code for that package in this file.
22
Importing modules from a Package
Create a folder names Pack outside your working folder. Now, Consider a file Asample.pyavailable
in pack directory. This file has following line of source code.
def a( ):
print (This is from A")
Similarly we have two more files Bsample.py and Csample.py available in pack directorywith
the following codes.
Bsample. py
def b( ):
print (This is from B")
Csample.py
def c( ):
print (This is from C")
Now we have three files in the same directory pack. To make all of our functions availablewhen we
are importing pack, we need to put explicit import statements in init .py as follows.
Import Pack.Asample
ImportPack.Bsample
Import Pack.Csample
After adding these lines to init__.py, we have all of these functions available when we are import
the pack package. The following code shows how the package pack can be imported.
import pack.
Asam.a( )
Bsam.b( )
Csam.c( )
23
from C
In the above example, we have defined only one function in each module. It is also possible to
have multiple definitions (more than one function) in each module and all these functionscan be
imported using the wildcard character „*‟. Likewise if we have subfolders each subfolder can be
separated by using dot operator while importing the package. For example,if the package pack
resides in /user/abc/level 1, we can give the import statement as follows.
FILE HANDLING
File is a named location on disk to store related information. It is used to permanently storedata in a
non-volatile memory (e.8. 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, afile operation
takes place in the following order.
a. Open a file
We have been reading and writing to the standard input and output. Now, we will see how touse
actual data files. Python provides basic functions and methods necessary to manipulate files by
default. We can do most of the file manipulation using a file object.
OPENING A FILE
Before we can read or write a file, we have to open it using Python's built-in open()function. This
function returns a file object, also called a handle, as it is used to read or modify the file
accordingly.
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 modeor binary
mode. The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to beused when dealing with
non-text files like image or exe files. The following shows the syntax for opening a file.
Syntax
filename: The filename argument is a string value that contains the name of the file that wewant
to access.
accessmode: The accesssmode determines the mode in which the file has to be opened. This is
optional parameter and the default file access mode is read(r).
buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is1, line
buffering is performed while accessing a file. If we specify the buffering value as an integer
greater than 1, then buffering action is performed with the indicated buffer size. If negative, the
buffer size is the system default. This is also an optional parameter.
Example
In the above example, the file abc.txt is opened in the current working directory in read modeand
sample.txt is opened in read mode inside C: \Python33 folder.
1. 'r‟- Opens a file for reading only. The file pointer is placed at the beginning of the file. Thisis
the default mode.
2. „rb‟-Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file.
3. 'r+'- Opens a file for both reading and writing. The file pointer is placed at the beginning ofthe
file.
4. 'rb+‟ - Opens a file for both reading and writing in binary format. The file pointer is placedat
the beginning of the file.
5. 'w‟-Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
6. 'wb'- Opens a file for writing only in binary format. Overwrites the file if the file exists. Ifthe
file does not exist, creates a new file for writing.
7. 'w+‟- Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
8. 'wb+' - Opens a file for both writing and reading in binary format. Overwrite the existingfile
if the file exists. If the file does not exist, creates a new file for reading and writing.
9. 'a‟ - Opens a file for appending. The file pointer is at the end of the file if the file exists.That
is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
10. „ab‟-open a file for appending in binary format. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for
writing
25
11. „a+‟-Opens a file for both appending and reading. The file pointer is at the end of the file if
the file exists. The file opens in the append mode. If the file does not exist, it creates a new file
for reading and writing.
12.‟ ab+‟-Opens a file for both appending and reading in binary format. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
13.‟x‟- Open a file for exclusive creation. If the file already exists, the operation fails.
Since the version 3.x, Python has made a clear distinction between str (text) and bytes(8- bits).Unlike
other languages, the character 'a‟ does not imply the number 97 until it is encoded using ASCII (or other
equivalent encodings). Hence, when working with files in node, it is recommended to specify the
encoding type. Files are stored in bytes in the disk, weneed to decode them into str when we read into
Python. Similarly, encoding is performed while writing texts to the file.
The default encoding is platform dependent. In windows, it is 'cp1252' but 'utf-8' in Linux.
Hence, we must not rely on the default encoding otherwise, our code will behave differentlyin
different platforms. Thus, this is the preferred way to open a file for reading in text mode.f = open
("abc. txt", mode = „r', encoding = „utf-8')
Once a file is opened, we have one file object, we can get various information related to thatfile.
The following shows various attributes for the file object.
The following example shows the working of the above described attributes of file object.
Example Program
26
Output
CLOSING A FILE
When we have finished the operations to a file, we need to properly close it. Python has a garbage
collector to clean up unreferenced objects. But we must not rely on it to close the file. Closing a
file will free up the resources that were tied with the file and is done using the close( ) method.
The following shows the syntax for closing a file.
Syntax
fileObject.close ()
Example Program
Output
WRITING TO A FILE
In order to write into a file we need to open it in write 'w, append 'a or exclusive creation 'x‟
mode. We need to be careful with the 'w‟ node as it will overwrite into the file if it already exists.
All previous data will be erased.
Writing a string or sequence of bytes (tor binary files) is done using write( ) method. This method
returns the number of characters written to the file. The write( ) method does not add a newline
character ("\n”) to the end of the string. The following shows the syntax of write( )method.
Syntax
fileobject.write (string)
27
Here, passed parameter string is the content to be written into the opened file
Example Program
fo = Open ("test.txt",”w”)
fo. write("Programming with Python is Fun. \nLet' s try Python!\n”)
# Close opened file
fo.close ()
print (“Flle", fo.name, "closed.")
Output
In the above program, we have opened a file test.txt in writing mode. The string to be writtenis
passed to the write ( ) method.
with Statement
Python with statement is handy when we have two related operations which we would like to
execute as a pair, with a block of code in between. The classic example is opening a file,
manipulating the file, then closing it.
Example Program
The above with statement will automatically close the file after the nested block of code. The
advantage of using a with statement is that it is guaranteed to close the file no matter how the nested
block exits. If an exception occurs before the end of the block, it will close the file before the
exception is caught by an outer exception handler. If the nested block were to contain a return
statement, or a continue or break statement, the with statement would automatically close the file in
those cases, also.
To read the content of a file, we must open the file in reading mode. The read ( ) method reads
a string from an open file. It is important to note that Python strings can have binary data, apart
from text data. The following gives the syntax for reading from a file.
28
Syntax
fileObject.read ([size])
Here, the passed parameter size is the number of bytes to be read from the opened file. This
method starts reading from the beginning of the file and if size is missing, then it tries to read as
much as possible, maybe until the end of file. The following example shows how to read from the
file test.txt which we have already created.
Example Program
Output
FILE METHODS
1. file.close( )
2. file.fileno( ) : Returns an integer number (file descriptor) of the file.
Example Program
Output
29
Example Program
5. file.write( )
6. file.read( )
7. file.readline( )-The method readline() reads one entire line from the file. A trailing newline
character is kept in the string. An empty string is returned only when EOF is encountered
immediately.
8. file.truncate([size] - The method truncate() truncates the file's size. If the optional size
argument is present, the file is truncated to (atmost) that size.
Example Program
# open a file
Output
9. file.readlines((sizeint]) - The method readlines( ) reads until EOF using readline( ) and
returns a list containing the lines. sizeint is an optional argument and if it is present, instead of
30
reading up to EOF, whole lines approximate to sizeint bytes are read. An empty string is returned only
when EOF is encountered immediately.
Example Program
#Open a file in write mode
fo=open ( "Demo. txt'","w")
seq=["First Line\n", "Second Line \n", "Third Line \n" , "Fourth Line \n", "Fifth Line \n"]
fo.writelines (seq)
#close the file
fo.close ( )
#Open the file in read mode
fo = open ("Demo. txt”,”r”)
line = fo.readlines ( )
print ("readlines( ):" line)
line= fo.readlines (2)
print ("readlines (2):",1ine)
#Close opened file
fo.close ()
Output
readlines (): [„First Line\n', „Second Line \n‟,‟ Third Line\n‟, „Fourth Line \n' ,‟Fifth Line\n']
readlines (2) : [ ]
RENAMING A FILE
The os module Python provides methods that help to perform file-processing operations, such as
renaming and deleting files. To use this os module, we need to import it first and then we can call
any related functions. To rename an existing file, we can use the rename( ) method. This method
takes two arguments, current filename and new filename. The following shows the syntax for
rename method.
Syntax
os.rename (current file _name, new_file_name)
Example Program
import os
#Rename a file from test.txt to Newtest.txt
os.rename ("test.txt", "Newtest.txt")
print (“File renamed.")
Output
File renamed.
DELETING A FILE
We can delete a file by using the remove( ) method available in os module. This method
receives one argument which is the filename to be deleted. The following gives the syntax for
remove() method.
31
Syntax
os.remove (filename)
Example Program
import os #Delete a file
os.remove ("Newtest.txt")
print ("File Deleted. ")
Output
File Deleted.
DIRECTORIES IN PYTHON
All files will be saved in various directories, and Python has efficient methods for handling
directories and files. The os module has several methods that help to create, remove and change
directories.
mkdir() method
The mkdir( ) method of the os module is used to create directories in the current directory. We need
to supply an argument to this method which contains the name of the directory to be created. The
Syntax
os.mkdir(“dirname”)
Example
import os
mkdir ("Fruits")
chdir( ) method
To change the current directory, we can use the chdir( ) method. The chdir ( ) method takes an
argument, which is the name of the directory that we want to make the current directory. The
Syntax
os.chdir("dirname")
32
Example
import os
# Change a directory
os.chdir ("/home/abc")
getcwd( ) method
The getcwd( ) method displays the current working directory. The following shows the syntax of
getcwd( ) method.
Syntax
os.getcwd( )
Example
import os
os.getcwd( )
rmdir() method
The rmdir( ) method deletes the directory, which is passed as an argument in the method.
Syntax
os.rmdir ("dirname")
Example
import os
Os.rmdir(“Fruits”)
It is intended to give the exact path of a directory. Otherwise it will search the current working
directory.
********************************
33