Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
24 views

Unit 2 Functions, OOP, Exceptions, Files

Uploaded by

Hell Gaming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Unit 2 Functions, OOP, Exceptions, Files

Uploaded by

Hell Gaming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Unit 2: Functions, OOP, Exceptions, Files

Python Functions
o Once defined, Python functions can be called multiple times and from any
location in a program.
o Our Python program can be broken up into numerous, easy-to-follow functions
if it is significant.
o The ability to return as many outputs as we want using a variety of arguments
is one of Python's most significant achievements.
o However, Python programs have always incurred overhead when calling
functions.

However, calling functions has always been overhead in a Python program.

Syntax

1. # An example Python Function


2. def function_name( parameters ):
3. # code block

The accompanying components make up to characterize a capability, as seen


previously.

o The start of a capability header is shown by a catchphrase called def.


o function_name is the function's name, which we can use to distinguish it from
other functions. We will utilize this name to call the capability later in the
program. Name functions in Python must adhere to the same guidelines as
naming variables.
o Using parameters, we provide the defined function with arguments.
Notwithstanding, they are discretionary.
o A colon (:) marks the function header's end.
o Several valid Python statements make up the function's body. The entire code
block's indentation depth-typically four spaces-must be the same.
o A return expression can get a value from a defined function.

Illustration of a User-Defined Function


We will define a function that returns the argument number's square when called.

1. # Example Python Code for User-Defined function


2. def square( num ):
3. """
4. This function computes the square of the number.
5. """
6. return num**2
7. object_ = square(6)
8. print( "The square of the given number is: ", object_ )

Output:

The square of the given number is: 36

Calling a Function
Calling a Function To define a function, use the def keyword to give it a name, specify
the arguments it must receive, and organize the code block.

When the fundamental framework for a function is finished, we can call it from
anywhere in the program. An illustration of how to use the a_function function can be
found below.

1. # Example Python Code for calling a function


2. # Defining a function
3. def a_function( string ):
4. "This prints the value of length of string"
5. return len(string)
6.
7. # Calling the function we defined
8. print( "Length of the string Functions is: ", a_function( "Functions" ) )
9. print( "Length of the string Python is: ", a_function( "Python" ) )

Output:

Length of the string Functions is: 9


Length of the string Python is: 6

Pass by Reference vs. Pass by Value


In the Python programming language, all parameters
are passed by reference.
Code

1. # Example Python Code for Pass by Reference vs. Value


2. # defining the function
3. def square( item_list ):
4. '''''''This function will find the square of items in the list'''
5. squares = [ ]
6. for l in item_list:
7. squares.append( l**2 )
8. return squares
9.
10. # calling the defined function
11. my_list = [17, 52, 8];
12. my_result = square( my_list )
13. print( "Squares of the list are: ", my_result )

Output:

Squares of the list are: [289, 2704, 64]

Function Arguments
The following are the types of arguments that we can use to call a function:

1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments

1) Default Arguments
Code

1. # Python code to demonstrate the use of default arguments


2. # defining a function
3. def function( n1, n2 = 20 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7.
8. # Calling the function and passing only one argument
9. print( "Passing only one argument" )
10. function(30)
11.
12. # Now giving two arguments to the function
13. print( "Passing two arguments" )
14. function(50,30)

Output:

Passing only one argument


number 1 is: 30
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30

def fun(a,x=30,y,b=10):

print("a=",a,"b=",b)

fun(1,20)

Output:

ERROR!

File "<string>", line 1

def fun(a,x=30,y,b=10):

^
SyntaxError: non-default argument follows default argument

>

Below works fine:

def fun(a,b=10,c=20):

print("a=",a,"b=",b,"c=",c)

fun(1,20)

Below works fine:

def fun(a=1,b=1,c=1):

print("a=",a,"b=",b,"c=",c)

fun()

2) Keyword Arguments
Code

1. # Python code to demonstrate the use of keyword arguments


2. # Defining a function
3. def function( n1, n2 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7. # Calling function and passing arguments without using keyword
8. print( "Without using keyword" )
9. function( 50, 30)
10.
11. # Calling function and passing arguments using keyword
12. print( "With using keyword" )
13. function( n2 = 50, n1 = 30) #param names must match

Output:

Without using keyword


number 1 is: 50
number 2 is: 30
With using keyword
number 1 is: 30
number 2 is: 50

Below works fine:

def fun(a=1,b=1,c=1):

print("a=",a,"b=",b,"c=",c)

fun(b=10,a=20)

Below works fine:

def fun(a=10,b=1,c=1):

print("a=",a,"b=",b,"c=",c)

fun(c=30,b=20)
3) Required Arguments
Code

1.
2. # Defining a function
3. def function( n1, n2 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7. # Calling function and passing two arguments out of order, we need num1 to be 20 a
nd num2 to be 30
8. print( "Passing out of order arguments" )
9. function( 30, 20 )
10.
11. # Calling function and passing only one argument
12. print( "Passing only one argument" )
13. try:
14. function( 30 )
15. except:
16. print( "Function needs two positional arguments" )

Output:

Passing out of order arguments


number 1 is: 30
number 2 is: 20
Passing only one argument
Function needs two positional arguments

4) Variable-Length Arguments

"args" and "kwargs" refer to arguments not based on


keywords.
Arbitrary Keyword Arguments, **kwargs

If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function
definition.
This way the function will receive a dictionary of arguments, and
can access the items accordingly:

If the number of keyword arguments is unknown, add a double ** before the


parameter name:

def my_function(**kid): #getting dictionary


print("His last name is " + kid["lname"]) #printing from Dictionary

my_function(fname = "amit", lname = "patel")

Arbitrary Kword Arguments are often shortened to **kwargs in Python


documentations.

To help you understand arguments of variable length, here's an example.

Code

1. # Python code to demonstrate the use of variable-length arguments


2. # Defining a function
3. def function( *args_list ):
4. ans = []
5. for l in args_list:
6. ans.append( l.upper() )
7. return ans
8. # Passing args arguments
9. object = function('Python', 'Functions', 'tutorial')
10. print( object )
11.
12. # defining a function
13. def function( **kargs_list ):
14. ans = []
15. for key, value in kargs_list.items():
16. ans.append([key, value])
17. return ans
18. # Paasing kwargs arguments
19. object = function(First = "Python", Second = "Functions", Third = "Tutorial")
20. print(object)
Output:

['PYTHON', 'FUNCTIONS', 'TUTORIAL']


[['First', 'Python'], ['Second', 'Functions'], ['Third', 'Tutorial']]

def fun(**a):
print(a) #it will print Dictionary

fun(c=30,b=20)

Output:
{'c': 30, 'b': 20}

Example:
def fun(c,**a,d):
print(a)
print(c)

fun(10,a=10,d=30)

Error:
ERROR!
File "<string>", line 1
def fun(c,**a,d):
^
SyntaxError: arguments cannot follow var-keyword
argument

Example
def fun(c=10,**a):
print(a)
print(c)

fun(a=10,d=30)

Output:
{'a': 10, 'd': 30}
10
Example:
def fun(b,c=10,**a):
print(a)
print(c)
fun(40,30)

Output:
{}
30
Example
def fun(**a):
print(a)
# print(c)

fun(40,30)
ERROR!
Traceback (most recent call last):
File "<string>", line 5, in <module>
TypeError: fun() takes 0 positional arguments but 2
were given

Example:
def fun(**a):
print(a)
print(c)

fun(40)
Output:
ERROR!
Traceback (most recent call last):
File "<string>", line 5, in <module>
TypeError: fun() takes 0 positional arguments but 1
was given

Example:
def fun(c,**a):
print(a)
print(c)

fun(40)

Output:
{}
40

Example:
def fun(c,**a):
print(a)
print(c)

fun(40,a=10,b=20)

Output:
{'a': 10, 'b': 20}
40
Example:
def fun(**b,**a):
print(a)
print(c)

fun(b=50,a=500)
Example:
ERROR!
File "<string>", line 1
def fun(**b,**a):
^^
SyntaxError: arguments cannot follow var-keyword
argument
Example
def fun(**a):
print(a)
#print(c)

fun()

Output:
{}

Example
def fun(**a):
print(a)
#print(c)
list=[1,2,3]
fun(b=list)

Output:
{'b': [1, 2, 3]}

Example:
def fun(**a):
print(a)
#print(c)
list=[1,2,3]
fun(list)

ERROR

Example:
def fun(c,**a):
print(a)
print(c)
list=[1,2,3]
fun(list,b=[4,5,6],x=[10,20,30],y="amit")

Output:
{'b': [4, 5, 6], 'x': [10, 20, 30], 'y': 'amit'}
[1, 2, 3]

Example:
def fun(c,x,**a):
print(a)

list=[1,2,3]
fun(list,10,d=20,a=50,x=100)
Error:
Traceback (most recent call last):
File "/home/cg/root/657ed8daed710/main.py", line 5,
in <module>
fun(list,10,d=20,a=50,x=100)
TypeError: fun() got multiple values for argument 'x'
def fun(p,a,x):
print(a)

list=[1,2,3]
fun(20,a=50,p=100)

Traceback (most recent call last):


File "/home/cg/root/657ed8daed710/main.py", line 5,
in <module>
fun(20,a=50,p=100)
TypeError: fun() got multiple values for argument 'p'

Example:
def fun(p,a,l):
print(a)

list=[1,2,3]
fun(20,a=50,90)

Output:
File "/home/cg/root/657ed8daed710/main.py", line 5
fun(20,a=50,90)
^
SyntaxError: positional argument follows keyword
argument
def fun(l):
return l*2

list=[1,2,3]
print(fun(list))

Output:
[1, 2, 3, 1, 2, 3]

def fun(**a):
return a

print(fun(a=10,b=20))
Output:
{'a': 10, 'b': 20}

Example:
def fun(**a):
a['a']=1000 #changing value in dictionary
return a

print(fun(a=10,b=20))

Output:
{'a': 1000, 'b': 20}

*args
def fun(*a):
print(*a)
print(a)
print(fun(10))

Output:
10
(10,)
None

Example:
def fun(*a):
print(*a)
print(a)
print(fun(10,20,30))

Output:
10 20 30
(10, 20, 30)
None

Example:
def fun(*a,c,d,b=1000):
print(*a)
print(f'a={a},b={b},c={c},d={d}')
print(a)
print(fun(10,d=110,c=20))

Output:
10
a=(10,),b=1000,c=20,d=110
(10,)
None

Example:
def fun(a=10,b=50,*c):
print(*c)
print(f'a={a},b={b},c={c}')
print(c)
print(fun(20,30))
Output:
a=20,b=30,c=()
()
None

Example:
def fun(a,b,**c,d):
print(c)

print(c)
print(fun(20,30,c=40,d=50))
Output:
File "/home/cg/root/657ed8daed710/main.py", line 1
def fun(a,b,**c,d):
^
SyntaxError: invalid syntax
Example:
def fun(*t):
print(t)
print(fun(111,222,[10,20,30],(40,50),{60,70},{"name":"
amit"}))

Output:
(111, 222, [10, 20, 30], (40, 50), {60, 70}, {'name':
'amit'})
None
When a defined function is called, a return statement is written to exit the function and
return the calculated value.

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.

This way the function will receive a tuple of arguments, and can access
the items accordingly:

If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("one", “two", "three")

Arbitrary Arguments are often shortened to *args in Python documentations.

Related Pages
return Statement
When a defined function is called, a return statement is written to exit the function and
return the calculated value.

Syntax:

1. return < expression to be returned as output >

The return statement can be an argument, a statement, or a value, and it is provided


as output when a particular job or function is finished. A declared function will return
an empty string if no return statement is written.

A return statement in Python functions is depicted in the following example.

Code

1. # Python code to demonstrate the use of return statements


2. # Defining a function with return statement
3. def square( num ):
4. return num**2
5.
6. # Calling function and passing arguments.
7. print( "With return statement" )
8. print( square( 52 ) )
9.
10. # Defining a function without return statement
11. def square( num ):
12. num**2
13.
14. # Calling function and passing arguments.
15. print( "Without return statement" )
16. print( square( 52 ) )
Output:

With return statement


2704
Without return statement
None

The Anonymous Functions (like lambda)


Since we do not use the def keyword to declare these kinds of Python functions,
they are unknown. The lambda keyword can define anonymous, short, single-
output functions.

Arguments can be accepted in any number by lambda expressions; However, the


function only produces a single value from them. They cannot contain multiple
instructions or expressions.

Lambda functions can only refer to variables in their argument list and the global
domain name because they contain their distinct local domain.

lambda expressions appear to be one-line representations of functions.

Syntax

Lambda functions have exactly one line in their syntax:

1. lambda [argument1 [,argument2... .argumentn]] : expression

Below is an illustration of how to use the lambda function:

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have
one expression.

Syntax
lambda arguments : expression

The expression is executed and the result is returned:


Add 10 to argument a, and return the result:

x = lambda a : a + 10
print(x(5))

Lambda functions can take any number of arguments:

Example
Multiply argument a with argument b and return the result:

x = lambda a, b : a * b
print(x(5, 6))

Example
Summarize argument a, b, and c and return the result:

x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

EXAMPLE
x = lambda **a : print(a)
print(x(a=6,b=8))

Output:
{'a': 6, 'b': 8}
None

EXAMPLE
x = lambda b,c,*a : print(a,b,c)
print(x(1,2,3,4))

Output:
(3, 4) 1 2
None

Example:
x = lambda b,*a,c=10 : print(a,b,c)
print(x(1,2,3,4))

Output:
(2, 3, 4) 1 10
None

Example:
x = lambda b,*a,c : print(a,b,c)
print(x(1,2,3,4))
Output:
Traceback (most recent call last):
File "/home/cg/root/657ed8daed710/main.py", line 2, in <module>
print(x(1,2,3,4))
TypeError: <lambda>() missing 1 required keyword-only argument: 'c'

Why Use Lambda Functions?


The power of lambda is better shown when you use them as an anonymous
function inside another function.

Say you have a function definition that takes one argument, and that
argument will be multiplied with an unknown number:

def myfunc(n):
return lambda a : a * n

Example
def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))

Example
def myfunc(n):
return lambda a : a * n
#it returns lambda function, not any value, returns lambda a:a*2 (i.e.
value of n)

mydoubler = myfunc(2)
# myfunc() returns lambda function that is saved in mydoubler, so my
doubler is now lambda function

print(mydoubler) #prints memory address of lambda function

print(mydoubler(11)) #calling lambda function

Or, use the same function definition to make a function that


always triples the number you send in:

Example
def myfunc(n):
return lambda a : a * n #returns lambda a: a*3
mytripler = myfunc(3) #mytripler is a lambda function

print(mytripler(11)) #calling lambda function

Or, use the same function definition to make both functions, in the same
program:

Example
def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11))
print(mytripler(11))

Use lambda functions when an anonymous function is required for a short


period of time.

Code

1. # Python code to demonstrate ananymous functions


2. # Defining a function
3. lambda_ = lambda argument1, argument2: argument1 + argument2;
4.
5. # Calling the function and passing values
6. print( "Value of the function is : ", lambda_( 20, 30 ) )
7. print( "Value of the function is : ", lambda_( 40, 50 ) )

Output:

Value of the function is : 50


Value of the function is : 90

Scope and Lifetime of Variables


A variable's scope refers to the program's domain wherever it is declaredThe lifespan
of a function is the same as the lifespan of its internal variables. When we exit the
function, function variables are taken away from us. As a result, the value of a variable
in a function does not persist from previous executions.
Code

1. # Python code to demonstrate scope and lifetime of variables


2. #defining a function to print a number.
3. def number( ):
4. num = 50
5. print( "Value of num inside the function: ", num)
6.
7. num = 10
8. number()
9. print( "Value of num outside the function:", num)

Output:

Value of num inside the function: 50


Value of num outside the function: 10

Here, we can see that the initial value of num is 10. Even though the function number()
changed the value of num to 50, the value of num outside of the function remained
unchanged.

Is it really pass by Reference in function calls?

def fun(a):

print(id(a)) #both ‘a’ have same id

a=20 #after assignment id(a) changed to new values

print(id(a)) #prints new id(a)

a=0

print(id(a))

fun(a)

print(a)

print(id(a))
Output:

140200934097104

140200934097104

140200934097744 #local ‘a’ after assignment in function, address of ‘a’ in function


changed

140200934097104 #’a’ outside function

Function inside a Function


A function defined within another is called an "inner" or "nested" function. The
parameters of the outer scope are accessible to inner functions.

Code

1. # Python code to show how to access variables of a nested functions


2. # defining a nested function
3. def word():
4. string = 'Python functions tutorial'
5. x=5
6. def number():
7. print( string )
8. print( x )
9.
10. number()
11. word()

Output:

Python functions tutorial


5

Nested (or inner) functions are functions defined within other functions that
allow us to directly access the variables and names defined in the enclosing
function.
Defining an inner/nested Function
Simply use the def keyword to initialize another function within a function to
define a nested function.

The following program is to demonstrate the inner function in Python −

Example

# creating an outer function


def outerFunc(sample_text):
sample_text = sample_text
# creating an inner function
def innerFunc():
# Printing the variable of the parent class(outer class)
print(sample_text)
# calling inner function
innerFunc()
# Calling the outer Function by passing some random name
outerFunc('Hello Amit')
innerFunc() #This will give error, you cannot call inner function outside outer
function

Output

On executing, the above program will generate the following output −

Hello Amit

Here, innerFunc() is declared inside the outerFunc(), making it an inner


function. We must first call outerFunc() before we can call innerFunc().
The outerFunc() will then call the innerFunc(), which is defined within it.

It is essential that the outer function be called so that the inner function can
execute.

Below will give not output as we have not called inner function

# creating an outer function


def outerFunc(sample_text):

# creating an inner function

def innerFunc():

# Printing the variable of the parent class(outer class)

print(sample_text)

# calling inner function

# Calling the outer Function by passing some random name

outerFunc('Hello Amit')

Without Calling Outer Function

Example

# creating an outer function


def outerFunc(sample_text):

# creating an inner function


def innerFunc():
print(sample_text)
# calling inner function
innerFunc()

Output

On executing, the above program will generate the following output −

When run, the above code will return no results.

Scope of Variable in Nested Function


The scope of a variable is the location where we can find a variable and access
it if necessary.
It is well-understood how to access a global variable within a function, but
what about accessing the variable of an outside function?

The following program demonstrates the scope of the nested functions −

Example

# creating an outer function


def outerFunc():
sample_str = 'Hello Amit'

# creating an inner function


def innerFunc():
print(sample_str)

# calling an inner function inside the outer function


innerFunc()
# calling outer function
outerFunc()

Output

On executing, the above program will generate the following output −

Hello Amit

It is clear from the above example that it is equivalent to accessing a global


variable from a function.

Assume you wish to modify the variable of the outer function.

Example

The following program changes the value of a variable inside the nested
function(inner function) −

# creating an outer function


def outerFunc():
sample_str = 'Hello Amit'
# creating an inner function
def innerFunc():
# modifying the sample string
sample_str = 'Welcome'
print(sample_str)
# calling an inner function inside the outer function
innerFunc()
print(sample_str)
# calling outer function
outerFunc()

Output

On executing, the above program will generate the following output −

Welcome
Hello Amit

Here, the value of the outer function's variable remains unchanged. However,
the value of the outer function's variable can be modified. There are several
methods for changing the value of the outer function's variable.

Printing IDs

# creating an outer function

def outerFunc():

sample_str = 'Hello Amit with outer ID'

print(id(sample_str))

# creating an inner function

def innerFunc():

# modifying the sample string

sample_str = 'Welcome with Innder ID'

print(sample_str)

print(id(sample_str))
# calling an inner function inside the outer function

innerFunc()

print(sample_str)

print(id(sample_str))

# calling outer function

outerFunc()

Output:

140591567492224

Welcome with Innder ID

140591565048688

Hello Amit with outer ID

140591567492224

>

Using an iterable of inner functions


The Following program demonstrates how to use modify iterables in inner
functions −

# Creating outer function


def outerFunc():
# Creating an iterable
sample_str = ['Hello Amit python']
# Creating inner Function/Nested Function
def innerFunc():
# using an iterable to modify the value
sample_str[0] = 'Welcome'
print(sample_str)
# Calling the inner function
innerFunc()
# Printing variable of the outer function
print(sample_str)
# Calling the outer function
outerFunc()

Output

On executing, the above program will generate the following output −

['Welcome']
['Welcome']

Example:

# Creating outer function


def outerFunc():
# Creating an iterable
sample_str = ['Hello Amit python']
# Creating inner Function/Nested Function
def innerFunc():
# using an iterable to modify the value
sample_str=["Hi PU","Hello students"]
print(sample_str)
sample_str[0] = 'Welcome to'
print(sample_str)
# Calling the inner function
innerFunc()
# Printing variable of the outer function
print(sample_str)
# Calling the outer function
outerFunc()

Output:
['Hi PU', 'Hello students']
['Welcome to', 'Hello students']
['Hello Amit python']

Why should you use nested functions?


Data encapsulation

There are cases when you wish to encapsulate a function or the data it has
access to in order to prevent it from being accessed from other parts of your
code.

When you nest a function like this, it becomes hidden to the global scope.
Because of this characteristic, data encapsulation is also known as data hiding
or data privacy.

# creating an outer function


def outerFunc():
print("This is outer function")
# creating an inner function
def innerFunc():
print("This is inner function")

# calling an inner function inside the outer function


innerFunc()
# calling inner function outside the outer function
innerFunc()

Output

On executing, the above program will generate the following output −

Traceback (most recent call last):


File "main.py", line 11, in <module>
innerFunc()
NameError: name 'innerFunc' is not defined

The inner function in the code above is only accessible from within the outer
function. If you attempt to call inner from outside the function, you will see
the error shown above.

Instead, you must call the outer function as follows.


# creating an outer function
def outerFunc():
print("This is outer function")
# creating an inner function
def innerFunc():
print("This is inner function")

# calling an inner function inside the outer function


innerFunc()
# calling outer function
outerFunc()

Output

On executing, the above program will generate the following output −

This is outer function


This is inner function

Python Lambda Functions


Lambda Functions are anonymous functions in Python. A lambda function can take n
number of arguments at a time. But it returns only one argument at a time.

What are Lambda Functions in Python?


Lambda Functions in Python are anonymous functions, implying they don't have a
name. The def keyword is needed to create a typical function in Python, as we already
know. We can also use the lambda keyword in Python to define an unnamed
function.

Syntax
The syntax of the Lambda Function is given below -

1. lambda arguments: expression

This function accepts any count of inputs but only evaluates and returns one
expression. That means it takes many inputs but returns only one output.

Lambda functions are limited to a single statement.


Example

1. # Code to demonstrate how we can use a lambda function for adding 4 numbers
2. add = lambda num: num + 4 #add variable/object points to the Lambda Function
3. print( add(6) )

Output:

10

Here we explain the above code. The lambda function is "lambda num: num+4" in the
given programme. The parameter is num, and the computed and returned equation is
num * 4.

There is no label for this function. It generates a function object associated with the
"add" identifier. We can now refer to it as a standard function.

Output:

Now we compile the above code in Python, and after successful compilation, we run
it. Then the output is given below -

10

Program Code

Now we gave an example of a lambda function that multiply 2 numbers and return
one result. The code is shown below -

1. a = lambda x, y : (x * y)
2. print(a(4, 5))

Output:

20

Program Code

1. a = lambda x, y, z : (x + y + z)
2. print(a(4, 5, 5))

Output:

14
What's the Distinction Between Lambda and Def
Functions?
This program calculates the reciprocal of a given number:

Program Code:

1. # Python code to show the reciprocal of the given number to highlight the difference
between def() and lambda().
2. def reciprocal( num ):
3. return 1 / num
4.
5. lambda_reciprocal = lambda num: 1 / num
6.
7. # using the function defined by def keyword
8. print( "Def keyword: ", reciprocal(6) )
9.
10. # using the function defined by lambda keyword
11. print( "Lambda keyword: ", lambda_reciprocal(6) )

Output:

Def keyword: 0.16666666666666666


Lambda keyword: 0.16666666666666666

Explanation:

Using Lambda: Instead of a "return" statement, Lambda definitions always include a


statement given at output. The beauty of lambda functions is their convenience..

Using Lambda Function with filter()


The filter() method accepts two arguments in Python: a function and an iterable
such as a list.

The function is called for every item of the list, and a new iterable or list is
returned that holds just those elements that returned True when supplied to the
function.

Here's a simple illustration of using the filter() method to return only odd numbers
from a list.
Program Code:

1. # This code used to filter the odd numbers from the given list
2. list_ = [35, 12, 69, 55, 75, 14, 73]
3. odd_list = list(filter( lambda num: (num % 2 != 0) , list_ ))
4. print('The list of odd number is:',odd_list)

Output:

The list of odd number is: [35, 69, 55, 75, 73]

Python map() Function

Example
Calculate the length of each word in the tuple:

def myfunc(n):
return len(n)

x = map(myfunc, ('apple', 'banana', 'cherry'))

Example:
def myfunc(a):
print(len(a))
return len(a) # returns len 5, then 6, then 6

x = map(myfunc, ('apple', 'banana', 'cherry'))


#passing one element at a time to myfunc() and
#creating map object with 5,6,6

print(x)#prints map object, not any values

#convert the map into a list, for readability:


print(list(x))
Definition and Usage
The map() function executes a specified function for each item(element) in an
iterable (like lists). The item is sent to the function as a parameter.

Syntax
map(function, iterables)

Parameter Values
Parameter Description

function Required. The function to execute for each item

iterable Required. A sequence, collection or an iterator object. You can send as


many iterables as you like, just make sure the function has one
parameter for each iterable.

More Examples
Example
Make new fruits by sending two iterable objects into the function:
Using Lambda Function with map()
A method and a list are passed to Python's map() function.

The function is executed for all of the elements within the list, and a new list is
produced with elements generated by the given function for every item.

The map() method is used to square all the entries in a list in this example.

Program Code:

Here we give an example of lambda function with map() in Python. Then code is given
below -

1. #Code to calculate the square of each number of a list using the map() function
2. numbers_list = [2, 4, 5, 1, 3, 7, 8, 9, 10]
3. squared_list = list(map( lambda num: num ** 2 , numbers_list ))
4. print( 'Square of each number in the given list:' ,squared_list )

Output:

Square of each number in the given list: [4, 16, 25, 1, 9, 49, 64, 81, 100]

List Comprehension
List comprehension offers a shorter syntax when you want to create a new
list based on the values of an existing list.

Example:

Based on a list of fruits, you want a new list, containing only the fruits with
the letter "a" in the name.

Without list comprehension you will have to write a for statement with a
conditional test inside:

Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
if "a" in x:
newlist.append(x)

print(newlist)

With list comprehension you can do all that with only one line of code:

Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)
The Syntax
newlist = [expression for item in iterable if condition == True]

The return value is a new list, leaving the old list unchanged.

Condition
The condition is like a filter that only accepts the items that valuate to True.

Example
Only accept items that are not "apple":

newlist = [x for x in fruits if x != "apple"]

The condition if x != "apple" will return True for all elements other than
"apple", making the new list contain all fruits except "apple".

The condition is optional and can be omitted:

Example
With no if statement:

newlist = [x for x in fruits]

Iterable
The iterable can be any iterable object, like a list, tuple, set etc.

Example
You can use the range() function to create an iterable:

newlist = [x for x in range(10)]

Same example, but with a condition:

Example
Accept only numbers lower than 5:

newlist = [x for x in range(10) if x < 5]

Expression
The expression is the current item in the iteration, but it is also the outcome,
which you can manipulate before it ends up like a list item in the new list:

Example
Set the values in the new list to upper case:

newlist = [x.upper() for x in fruits]

You can set the outcome to whatever you like:

Example
Set all values in the new list to 'hello':

newlist = ['hello' for x in fruits]

Using Lambda Function with if-else


We will use the lambda function with the if-else block. In the program code below, we
check which number is smaller than the given two numbers using the if-else block.

Program Code:

1. # Code to use lambda function with if-else


2. Minimum = lambda x, y : x if (x < y) else y
3. print('The smaller number is:', Minimum( 35, 74 ))

Output:

The smaller number is: 35

A lambda function can take n number of arguments at a time. But it returns only
one argument at a time.
Python File Handling
Python File Handling
Introduction:
The file handling plays an important role when the data needs to be stored
permanently into the file. A file is a named location on disk to store related
information. We can access the stored information (non-volatile) even after the
program termination.

In Python, files are treated in two modes as text or binary. The file may be in the
text or binary format, and each line of a file is ended with the special character like
a comma (,) or a newline character. Python executes the code line by line. So, it
works in one line and then asks the interpreter to start the new line again. This is a
continuous process in Python.

Hence, a file operation can be done in the following order.

o Open a file
o Read or write or append to a file
o Close the file

Opening a file
A file operation starts with the file opening. At first, open the File then Python will start
the operation. File opening is done with the open() function in Python. This function
will accepts two arguments, file name and access mode in which the file is accessed.
When we use the open() function, that time we must be specified the mode for
which the File is opening. The function returns a file object which can be used to
perform various operations like reading, writing, etc.

Syntax:

The syntax for opening a file in Python is given below -

1. file object = open(<file-name>, <access-mode>, <buffering>)

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.
SN Access Description
mode

1 r (default) r means to read. So, it opens a file for read-only operation. The file
pointer exists at the beginning. The file is by default open in this mode
if no access mode is passed.

2 rb It opens the file to read-only in binary format. The file pointer exists
at the beginning of the file.

3 r+ It opens the file to read and write both. The file pointer exists at the
beginning of the file.

4 rb+ It opens the file to read and write both in binary format. The file
pointer exists at the beginning of the file.

5 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.

6 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. The file pointer
exists at the beginning of the file.

7 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.

8 wb+ It opens the file to write and read both in binary format. The file
pointer exists at the beginning of the file.

9 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.

10 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.

11 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.
12 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.

Program code for read mode:

It is a read operation in Python. We open an existing file with the given code and then
read it. The code is given below -

1. #opens the file file.txt in read mode


2. fileptr = open("file.txt","r")
3.
4. if fileptr:
5. print("file is opened successfully")

Output:

Now we compile the above code in Python, and after successful compilation, we run
it. Then the output is given below -

file is opened successfully

In the above code, we have passed filename as a first argument and opened file in
read mode as we mentioned r as the second argument. The fileptr holds the file
object and if the file is opened successfully, it will execute the print statement

Program code for Write Mode:

It is a write operation in Python. We open an existing file using the given code and
then write on it. The code is given below -

1. file = open('file.txt','w')
2. file.write("Here we write a command")
3. file.write("Hello users of PARUL MIS")
4. file.close()

The close() Method


The close method used to terminate the program. Once all the operations are done
on the file, we must close it through our Python script using the close() method. Any
unwritten information gets destroyed once the close() method is called on a file
object.

We can perform any operation on the file externally using the file system which is the
currently opened in Python; hence it is good practice to close the file once all the
operations are done. Earlier use of the close() method can cause the of destroyed some
information that you want to write in your File.

The syntax to use the close() method is given below.

Syntax

The syntax for closing a file in Python is given below -

1. fileobject.close()

Consider the following example.

Program code for Closing Method:

Here we write the program code for the closing method in Python. The code is given
below -

1. # opens the file file.txt in read mode


2. fileptr = open("file.txt","r")
3.
4. if fileptr:
5. print("The existing file is opened successfully in Python")
6.
7. #closes the opened file
8. fileptr.close()

After closing the file, we cannot perform any operation in the file. The file needs to be
properly closed. If any exception occurs while performing some operations in the file
then the program terminates without closing the file.

We should use the following method to overcome such type of problem.

1. try:
2. fileptr = open("file.txt")
3. # perform file operations
4. finally:
5. fileptr.close()

The with statement


The with statement was introduced in python 2.5. The with statement is useful in the
case of manipulating the files.

Syntax:

The syntax of with statement of a file in Python is given below -

1. with open(<file name>, <access mode>) as <file-pointer>:


2. #statement suite

The advantage of using with statement is that it provides the guarantee to close
the file regardless of how the nested block exits.

It is always suggestible to use the with statement in the case of files because, if
the break, return, or exception occurs in the nested block of code then it
automatically closes the file, we don't need to write the close() function. It
doesn't let the file to corrupt.

Program code 1 for with statement:

Here we write the program code for with statement in Python. The code is given below:

1. with open("file.txt",'r') as f:
2. content = f.read();
3. print(content)

Program code 2 for with statement:

Here we write the program code for with statement in Python. The code is given below
-

1. with open("file.txt", "w") as f:


2. A = f.write("Hello Coders")
3. Print(A)

with open('demoText2.txt','w') as filePtr:


fileData=filePtr.write("hi\nhello\ngood morning\ngood
bye")
print(fileData)

file.write() returns number of characters written in the file

Writing the file


To write some text to a file, we need to open the file using the open method and then
we can use the write method for writing in this File. If we want to open a file that does
not exist in our system, it creates a new one. On the other hand, if the File exists, then
erase the past content and add new content to this File. It is done by the following
access modes.

w: It will overwrite the file if any file exists. The file pointer is at the beginning of the
file.

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.

Program code 1 for Write Method:

1. # open the file.txt in append mode. Create a new file if no such file exists.
2. fileptr = open("file2.txt", "w")
3.
4. # appending the content to the file
5. fileptr.write('Python is the modern programming language. It is done any kind of pro
gram in shortest way.')
6.
7. # closing the opened the file
8. fileptr.close()

Output:

Now we compile the above code in Python, and after successful compilation, we run
it. Then the output is given below -

File2.txt
Python is the modern programming language. It is done any kind of program
in shortest way.

We have opened the file in w mode. The file1.txt file doesn't exist, it created a new file
and we have written the content in the file using the write() function
Program code 2 for Write Method:

with open('demoText.txt', 'w') as file2:


file2.write('Hello coders\n')
file2.write('Welcome to parul MIS')

Error:

Traceback (most recent call last):

File
"C:\Users\dell\PycharmProjects\pythonProject2\GUIpythonProject\FilesNonGUI\open
File.py", line 3, in <module>

file2.write('Welcome to parul MIS')

ValueError: I/O operation on closed file.

Note: At the end of the block of WITH, file is automatically closed. So, you cannot
access that file outside the WITH block.

Here we write the program code for write method in Python. The code is given below
-

1. with open(test1.txt', 'w') as file2:


2. file2.write('Hello coders\n')
3. file2.write('Welcome to parul MIS')

Output:

Now we compile the above code in Python, and after successful compilation, we run
it. Then the output is given below -

Hello coders
Welcome to parul MIS

Program code 3 for Write Method:

Here we write the program code for write method in Python. The code is given below
-
1. #open the file.txt in write mode.
2. fileptr = open("file2.txt","a")
3.
4. #appending the content of the file
5. fileptr.write(" Python has an easy syntax and user-friendly interaction.")
6.
7. #closing the opened file
8. fileptr.close()

We can see that the content of the file is appended/modified. We have opened the file
in a mode and it appended the content in the existing file2.txt.

Read(count=number of characters/bytes)
The Python provides the read(no. of characters) method. It returns string. It can read
the data in the text as well as a binary format.

Syntax:

1. fileobj.read(<count>)

Here, the count is the number of bytes/characters 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.

Program code for read() Method:

fileptr = open("demoText.txt","r")
#stores all the data of the file into the variable content

allData=fileptr.read()
print(type(allData)) # prints string object
#prints the content of the file
print(allData)

firstTenBytes = fileptr.read(10)
print(firstTenBytes) #fileptr at end so will not print
anything
fileptr.seek(0) #reset fileptr to first character in the file
firstTenBytes=fileptr.read(10)

print(firstTenBytes)
#prints first 10 characters
#closes the opened file
fileptr.close()

Output:

<class 'str'>

my name is amit

some students talk too much during lectures/labs

some use mobile phones

i need to punish them as demo students to set them as examples

my name is

We have passed count value as ten which means it will read the first ten
characters/bytes from the file.

If we use the following line, then it will print all content of the file.

1. content = fileptr.read()
2. print(content)

Read file through for loop


We can read the file using for loop. Consider the following example.

Program code 1 for Read File using For Loop:

Here we give an example of read file using for loop. The code is given below -

1. #open the file.txt in read mode. causes an error if no such file exists.
2. fileptr = open("file2.txt","r")
3. #running a for loop
4. for i in fileptr:
5. print(i) # i contains each line of the file

Output:
Python is the modern day language.

It makes things so simple.

Python has easy syntax and user-friendly interaction.

fileptr = open("demoText.txt","r")
#running a for loop
print(fileptr)
for i in fileptr.read():
print(i) # prints character by character

fileptr.seek(0)
for i in fileptr:
print(i) #print line by line

<_io.TextIOWrapper name='demoText.txt' mode='r' encoding='cp1252'>


I

a
m

A
m
i
t
I am Amit

Program code 2 for Read File using For Loop:

1. A = ["Hello\n", "Coders\n", "Parul MIS\n"]


2. f1 = open('myfile.txt', 'w')
3. f1.writelines(A)
4. f1.close()
5. f1 = open('myfile.txt', 'r')
6. Lines = f1.read()
7. count = 0
8. for line in Lines:
9. count += 1
10. print("Line{}: {}".format(count, line))
Output:

Line1: H
Line2: e
Line3: l
Line4: l
Line5: o
Line6:
Line7: C
Line8: o
Line9: d
Line10: e
Line11: r
Line12: s
Line13:

A = ["Hello\n", "Coders\n", "Parul MIS\n"]

print("A=",A)
f1 = open('demoText.txt', 'w')
f1.writelines(A)
f1.close()
f1 = open('demoText.txt', 'r')
Lines = f1.read()
print(type(Lines)) #prints string object
print("data=",Lines) #prints all lines in file

for myChar in Lines:


print(myChar)

print(f1) #file IO object


count = 0
f1.seek(0)
for line in f1:
count += 1
print("Line{}: {}".format(count, line))

Output:
A= ['Hello\n', 'Coders\n', 'Parul MIS\n']
<class 'str'>
data= Hello
Coders
Parul MIS

H
e
l
l
o

C
o
d
e
r
s

P
a
r
u
l

M
I
S

<_io.TextIOWrapper name='demoText.txt' mode='r' encoding='cp1252'>


Line1: Hello

Line2: Coders

Line3: Parul MIS

Read Lines of the file


Python facilitates to read the file line by line by using a function readline() method.
The readline() method reads the lines of the file from the beginning, i.e., if we use the
readline() method two times, then we can get the first two lines of the file.

Consider the following example which contains a function readline() that reads the
first line of our file "file2.txt" containing three lines. Consider the following example.

1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","r");
3. #stores first line of the file into the variable content
4. content = fileptr.readline()
5. content1 = fileptr.readline() #stores second line of the file
6. #prints the content of the file
7. print(content) #prints first line
8. print(content1) #prints second line
9. #closes the opened file
10. fileptr.close()

Output:

Python is the modern day language.

It makes things so simple.

#open the file.txt in read mode. causes error if no such file


exists.
fileptr = open("myfile.txt","r");
#stores all the data of the file into the variable content
oneLine = fileptr.readline()
print("oneLine=",oneLine)
secondLine = fileptr.readline()
#prints the content of the file

print(secondLine)
#closes the opened file
fileptr.close()

oneLine= Hello

Coders

#open the file.txt in read mode. causes error if no such file


exists.
fileptr = open("myfile.txt","r")
#stores all the data of the file into the variable content
for line in fileptr.readline():
print(line)

H
e
l
l
o
We called the readline() function two times that's why it read two lines from the
file.That means, if you called readline() function n times in your program, then it read
n number of lines from the file. This is the uses of readline() function in Python.

#open the file.txt in read mode. causes error if no such file


exists.
fileptr = open("myfile.txt","r")
#stores all the data of the file into the variable content
line=fileptr.readline()

while(line):
print(line)
line=fileptr.readline()

this is first line

this is line two

this is third line

Python provides readlines() method which is used for the reading lines. It returns the
list of the lines till the end of file(EOF) is reached.

Example 2:

1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file.txt","r");
3.
4. #stores all the data of the file into the variable content
5. listOfLines= fileptr.readlines()
6.
7. #prints the content of the file
8. print(listOfLines)
9.
10. #closes the opened file
11. fileptr.close()
Output:

['Python is the modern day language.\n', 'It makes things so simple.\n',


'Python has easy syntax and user-friendly interaction.']

Example 3:

Here we give the example of reading the lines using the readlines() function in Python.
The code is given below -

1. A = ["Hello\n", "Coders\n", "Parul MIS\n"] #string of list


2. f1 = open('myfile.txt', 'w')
3. f1.writelines(A)
4. f1.close()
5. f1 = open('myfile.txt', 'r')
6. Lines = f1.readlines() #Lines is a list of Lines in the file
7. count = 0
8. for line in Lines: #Lines= list of Lines in the file
9. count += 1
10. print("Line{}: {}".format(count, line))

Output:

Line1: Hello
Line2: Coders
Line3: Parul MIS

Creating a new file


The new file can be created by using one of the following access modes with the
function open().The open() function used so many parameters. The syntax of it is given
below -

file = open(path_to_file, mode)

x, a and w is the modes of open() function. The uses of these modes are given below

x: it creates a new file with the specified name. It causes an error if a file exists
with the same name.

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 file.

Consider the following example.

Program code1 for Creating a new file:

Here we give an example for creating a new file in Python. For creates a file, we have
to use the open() method. The code is given below -

1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","x")
3. print(fileptr)
4. if fileptr:
5. print("File created successfully")

Output:

Now we compile the above code in Python, and after successful compilation, we run
it. Then the output is given below -

<_io.TextIOWrapper name='file2.txt' mode='x' encoding='cp1252'>


File created successfully

Program code2 for creating a new file with try-except:

try:
fileptr=open("demoText.txt",'x')
except FileExistsError as error:
print(str(error)+"\nFile already exists!")

[Errno 17] File exists: 'demoText.txt'

File already exists!

File Pointer positions


Python provides the tell() method which is used to print the byte number at which the
file pointer currently exists. The tell() methods returns the position of read or write
pointer in this file. The syntax of tell() method is given below -

1. fileobject.tell()

Program code1 for File Pointer Position:


1. # open the file file2.txt in read mode
2. fileptr = open("file2.txt","r")
3.
4. #initially the filepointer is at 0
5. print("The filepointer is at byte :",fileptr.tell())
6.
7. #reading the content of the file
8. content = fileptr.read();
9.
10. #after the read operation file pointer modifies. tell() returns the location of the fileptr.

11.
12. print("After reading, the filepointer is at:",fileptr.tell())

Output:

The filepointer is at byte : 0


After reading, the filepointer is at: 117

Program code2 for File Pointer Position:

1. file = open("File2.txt", "r")


2. print("The pointer position is: ", file.tell())

Output:

The pointer position is: 0

Modifying file pointer position (seek())


In real-world applications, sometimes we need to change the file pointer location
externally since we may need to read or write the content at various locations.

For this purpose, the Python provides us the seek() method which enables us to modify
the file pointer position externally. That means, using seek() method we can easily
change the cursor location in the file, from where we want to read or write a file.

Syntax:

The syntax for seek() method is given below -


1. <file-ptr>.seek(offset[, from])

The seek() method accepts two parameters:

Offset (MANDATORY): 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.

Consider the following example.

Here we give the example of how to modifying the pointer position using seek()
method in Python. The code is given below -

1. # open the file file2.txt in read mode


2. fileptr = open("file2.txt","r")
3.
4. #initially the filepointer is at 0
5. print("The filepointer is at byte :",fileptr.tell())
6.
7. #changing the file pointer location to 10.
8. fileptr.seek(10);
9.
10. #tell() returns the location of the fileptr.
11. print("After reading, the filepointer is at:",fileptr.tell())

Output:

Now we compile the above code in Python, and after successful compilation, we run
it. Then the output is given below -

The filepointer is at byte : 0


After reading, the filepointer is at: 10

file = open("demoText.txt", "r")


print(file.read())

file.seek(0)
print(file.read(1))
print("The pointer position is: ", file.tell())
file.seek(11,0)
print(file.read(1))
print("The pointer position is: ", file.tell())

file.seek(22,0)
print(file.read(1))
print("The pointer position is: ", file.tell())

123456789
abcdefghi
ABCDEFGHI
1
The pointer position is: 1
a
The pointer position is: 12
A
The pointer position is: 23

Python OS module:
Renaming the file
The Python os module enables interaction with the operating system. It comes from
the Python standard utility module. The os module provides a portable way to use the
operating system-dependent functionality in Python. The os module provides the
functions that are involved in file processing operations like renaming, deleting, etc. It
provides us the rename() method to rename the specified file to a new name. Using
the rename() method, we can easily rename the existing File. This method has not any
return value. The syntax to use the rename() method is given below.

Syntax:

The syntax of rename method in Python is given below -

1. rename(current-name, new-name)

The first argument is the current file name and the second argument is the modified
name. We can change the file name by passing these two arguments.

Program code 1 for rename() Method:


Here we give an example of the renaming of the files using rename() method in Python.
The current file name is file2.txt, and the new file name is file3.txt. The code is given
below -

1. import os
2.
3. #rename file2.txt to file3.txt
4. os.rename("file2.txt","file3.txt")
from os import *

#rename file2.txt to file3.txt


rename("demoText.txt","mydemoText.txt")

Removing the file


The os module provides the remove() method which is used to remove the specified
file.

Syntax:

The syntax of remove method is given below -

1. remove(file-name)

Program code 1 for remove() method:

1. import os;
2. #deleting the file named file3.txt
3. os.remove("file3.txt")
Method Description

file.close() It closes the opened file. The file once closed, it can't be read or
write anymore.

File.next() It returns the next line from the file.

File.read([size]) It reads the file for the specified size.

File.readline([size]) It reads one line from the file and places the file pointer to the
beginning of the new line.

File.readlines([sizehint]) It returns a list containing all the lines of the file. It reads the file until
the EOF occurs using readline() function.

File.seek(offset[,from) It modifies the position of the file pointer to a specified offset with
the specified reference.

File.tell() It returns the current position of the file pointer within the file.

File.truncate([size]) It truncates the file to the optional specified size or the current
cursor position, remaining data will be truncated.

File.write(str) It writes the specified string to a file

File.writelines(seq) It writes a sequence of the strings to a file.

You might also like