0% found this document useful (0 votes)
7 views

PY Mod 2

The document provides an overview of functions in Python, including how to define and call them, pass arguments, and use recursion. It also covers anonymous functions (lambda functions), modules and packages, and the import statement for utilizing built-in and user-defined modules. Additionally, it explains namespaces, scope, and the dir() function for listing attributes in a module.

Uploaded by

colade5740
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

PY Mod 2

The document provides an overview of functions in Python, including how to define and call them, pass arguments, and use recursion. It also covers anonymous functions (lambda functions), modules and packages, and the import statement for utilizing built-in and user-defined modules. Additionally, it explains namespaces, scope, and the dir() function for listing attributes in a module.

Uploaded by

colade5740
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

Functions in Python
In Python a function is defined using the def keyword:

def my_function():

print("Hello from a function")

A function is a set of statements that take inputs, do some specific computation and produces output. The
idea is to put some commonly or repeatedly done task together and make a function, so that instead of
writing the same code again and again for different inputs, we can call the function. Python provides built-
in functions like print(), etc. but we can also create your own functions. These functions are called user-
defined functions.

# A simple Python function to check whether x is even or odd

def evenOdd( x ):
if (x % 2 == 0):
print( "even")
else:
print( "odd")
evenOdd(2)
evenOdd(3)
Output:
even
odd
One important thing to note is, in Python every variable name is a reference. When we pass a variable to a
function, a new reference to the object is created. Parameter passing in Python is same as reference passing
in Java.

Calling a Function

To call a function, use the function name followed by parenthesis:

def my_function():

print("Hello from a function")

my_function()

Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments
as you want, just separate them with a comma. The following example has a function with one argument
(fname). When the function is called, we pass along a first name, which is used inside the function to print
the full name:

def my_function(fname):
print(fname + " Kapoor")
my_function("Anil")
my_function("Kareena")
my_function("Sonam")

1 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

From a function's perspective:

• A parameter is the variable listed inside the parentheses in the function definition.
• Arguments are the values that are sent to the function when it is called.

Passing a List as an Argument

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be
treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the function:

def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)

Return Values

To let a function return a value, use the return statement:

def my_function(x):

return 5 * x

print(my_function(3))

print(my_function(5))

print(my_function(9))

The pass Statement

function definitions cannot be empty, but if you for some reason have a function definition with no content,
put in the pass statement to avoid getting an error.

def myfunction():
pass

Recursion

Python also accepts function recursion, which means a defined function can call itself.

Recursion is a common mathematical and programming concept. It means that a function calls itself. This
has the benefit of meaning that you can loop through data to reach a result.

The developer should be very careful with recursion as it can be quite easy to slip into writing a function
which never terminates, or one that uses excess amounts of memory or processor power. However, when
written correctly recursion can be a very efficient and mathematically-elegant approach to programming.

#Factorial of a number using recursion

def fact(i):
if i==1:

2 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

return 1
else:
return i*fact(i-1)
a=int(input("Enter a number : "))
print("Factorial of "+str(a)+" is "+str(fact(a)))
Anonymous Functions (Lambda Functions)
Python Lambda Functions are anonymous function means that the function is without a name. As we
already know that the def keyword is used to define a normal function in Python. Similarly,
the lambda keyword is used to define an anonymous function in Python.

Syntax: lambda arguments : expression

This function can have any number of arguments but only one expression, which is evaluated and returned.
One is free to use lambda functions wherever function objects are required. You need to keep in your
knowledge that lambda functions are syntactically restricted to a single expression. It has various uses in
particular fields of programming, besides other types of expressions in functions.

Here's the basic syntax of a lambda function:

lambda arguments: expression

Here's an example to illustrate how lambda functions work:

# Example 1: Adding two numbers using a lambda function

add = lambda x, y: x + y

result = add(3, 4)

print(result) # Output: 7

In this example, we define a lambda function that takes two arguments (x and y) and returns their sum. We
then assign this lambda function to the variable add. We can call add with two numbers, and it will return
their sum.

Lambda functions can take any number of arguments, including zero. Here's an example with zero
arguments:

# Example 2: Creating a lambda function with zero arguments

greet = lambda: "Hello, World!"

message = greet()

print(message) # Output: "Hello, World!"

Lambda functions can also be used in combination with built-in functions like map(), filter(), and reduce().
For instance:

# Example 3: Using a lambda function with map()

numbers = [1, 2, 3, 4, 5]

3 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

squared = list(map(lambda x: x**2, numbers))

print(squared) # Output: [1, 4, 9, 16, 25]

In this example, the map() function applies the lambda function (which squares a number) to each element
in the numbers list, resulting in a list of squared numbers.

Lambda functions are particularly useful in situations where you need a simple, short-lived function
without the need for a formal function definition. Keep in mind that they are best suited for small, single-
purpose operations. If your code requires complex logic or readability is a concern, it's usually better to use
a named function.

Example 4

In the example, we defined a lambda function(upper) to convert a string to its upper case using upper().

str1 = 'Naipunnya School of Management'

upper = lambda string: string.upper()

print(upper(str1))

Example 5

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

mydoubler = myfunc(2)

mytripler = myfunc(3)

print(mydoubler(11))

print(mytripler(11))

Modules & Packages in Python

Python modules are individual Python files that can be reused in other Python programs. They allow you
to organize your code into smaller, manageable pieces, making it easier to maintain and understand. A
module can define functions, classes, and variables. A module can also include runnable code. Grouping
related code into a module makes the code easier to understand and use. It also makes the code logically
organized. Modules can be either built-in, provided by Python itself, or created by users.

Built-in Modules

Python comes with a rich set of built-in modules that provide a wide range of functionalities. These modules
cover areas like file I/O, mathematics, system interfaces, and more. Some popular built-in modules include
math, os, random, and datetime.

# importing built-in module math


import math

# using square root(sqrt) function contained in math module


print(math.sqrt(25))

4 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

# using pi function contained in math module


print(math.pi)

# 2 radians = 114.59 degrees


print(math.degrees(2))

# 60 degrees = 1.04 radians


print(math.radians(60))

# Sine of 2 radians
print(math.sin(2))

# Cosine of 0.5 radians


print(math.cos(0.5))

# Tangent of 0.23 radians


print(math.tan(0.23))

# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))

# importing built in module random


import random

# printing random integer between 0 and 5


print(random.randint(0, 5))

# print random floating point number between 0 and 1


print(random.random())

# random number between 0 and 100


print(random.random() * 100)

List = [1, 4, True, 800, "python", 27, "hello"]

# using choice function in random module for choosing


# a random element from a set such as a list
print(random.choice(List))

# importing built in module datetime


import datetime
from datetime import date
import time

# Returns the number of seconds since the Unix Epoch, January 1st 1970
print(time.time())

5 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

# Converts a number of seconds to a date object


print(date.fromtimestamp(454554))

Creating Modules

Creating your own modules is straightforward. Simply save your Python code in a separate .py file and it
becomes a module. You can then import and use it in other Python scripts.

calc.py

# A simple module, calc.py


def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)

The import Statement

The import statement is used to bring in modules into your current Python script. It allows you to access
the functions, classes, and variables defined in the module.

import module_name

# importing module calc.py


import calc
print(calc.add(10, 2)
Import Specific Attributes from a Python module

Here, we are importing specific sqrt and factorial attributes from the math module.

# importing sqrt() and factorial from the


# module math
from math import sqrt, factorial

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))

The use of * has its advantages and disadvantages. If you know exactly what you will be needing from the
module, it is not recommended to use *, else do so.

# importing sqrt() and factorial from the module math


from math import *

# "import math", then math.sqrt(16) and math.factorial() are enough

6 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

print(sqrt(16))
print(factorial(6))

Locating Modules

Python searches for modules in specific directories. These directories are defined in the sys.path variable.
You can add your own directories to this list to make your modules accessible. Whenever a module is
imported in Python the interpreter looks for several locations. First, it will check for the built-in module, if
not found then it looks for a list of directories defined in the sys.path. Python interpreter searches for the
module in the following manner –

1. First, it searches for the module in the current directory.


2. If the module isn’t found in the current directory, Python then searches each directory in the shell
variable PYTHONPATH. The PYTHONPATH is an environment variable, consisting of a list of
directories.
3. If that also fails python checks the installation-dependent list of directories configured at the time
Python is installed.

Directories List for Modules

Here, sys.path is a built-in variable within the sys module. It contains a list of directories that the interpreter
will search for the required module.

# importing sys module


import sys

# importing sys.path
print(sys.path)

Namespaces and Scope

Modules provide a way to create separate namespaces for your variables and functions. This helps in
avoiding naming conflicts. You can access the items in a module using dot notation, like module_name.item.

A namespace is a system that has a unique name for each and every object in Python. An object might be a
variable or a method. Python itself maintains a namespace in the form of a Python dictionary. Let’s go
through an example, a directory-file system structure in computers. Needless to say, that one can have
multiple directories having a file with the same name inside every
directory. But one can get directed to the file, one wishes, just by specifying
the absolute path to the file.

When Python interpreter runs solely without any user-defined modules,


methods, classes, etc. Some functions like print(), id() are always present,
these are built-in namespaces. When a user creates a module, a global
namespace gets created, later the creation of local functions creates the
local namespace. The built-in namespace encompasses the global
namespace and the global namespace encompasses the local
namespace.

7 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

The lifetime of a namespace :

A lifetime of a namespace depends upon the scope of objects, if the scope of an object ends, the lifetime of
that namespace comes to an end. Hence, it is not possible to access the inner namespace’s objects from an
outer namespace.

# var1 is in the global namespace


var1 = 5
def some_func():
# var2 is in the local namespace
var2 = 6
def some_inner_func():
# var3 is in the nested local namespace
var3 = 7
But in some cases, one might be interested in updating or processing global variables only, as shown in the
following example, one should mark it explicitly as global and the update or process. Note that the line
“count = count +1” references the global variable and therefore uses the global variable, but compare this
to the same line written “count = 1”. Then the line “global count” is absolutely needed according to scope
rules.

# Python program processing global variable


count = 5
def some_method():
global count
count = count + 1
print(count)
some_method()

Scope refers to the coding region from which a particular Python object is accessible. Hence one cannot
access any particular object from anywhere from the code, the accessing has to be allowed by the scope of
the object.

# Python program showing a scope of object

def some_func():
print("Inside some_func")
def some_inner_func():
var = 10
print("Inside inner function, value of var:",var)
some_inner_func()
print("Try printing var from outer function: ",var)
some_func()

Output:

Inside some_func
Inside inner function, value of var: 10
NameError: name 'var' is not defined
8 Naipunnya School of Management, Cherthala [Jithin Babu]
S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

dir()

The dir() function is used to get a list of names defined in a module. It returns a sorted list of strings
containing the names of all the attributes in the given module.

import module_name

print(dir(module_name))

dir() tries to return a valid list of attributes of the object it is called upon. Also, dir() function behaves rather
differently with different type of objects, as it aims to produce the most relevant one, rather than the
complete information.

• For Class Objects, it returns a list of names of all the valid attributes and base attributes as well.
• For Modules/Library objects, it tries to return a list of names of all the attributes, contained in that
module.
• If no parameters are passed it returns a list of names in the current local scope.

# Python3 code to demonstrate dir() when no parameters are passed

# Note that we have not imported any modules


print(dir())

# Now let's import two modules


import random
import math

# return the module names added to the local namespace including all
# the existing ones as before
print(dir())

Output :

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__','__name__', '__package__', '__spec__', 'math',


'random']

# When a list object is passed as parameters for the dir() function

# A list, which contains a few random values


nsm = ["Naipunnya", "School", "of","Management", "Cherthala" ]

# dir() will also list out common attributes of the dictionary


d = {} # empty dictionary

# dir() will return all the available list methods in current local scope
print(dir(nsm))

9 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

# Call dir() with the dictionary name "d" as parameter. Return all
# the available dict methods in the current local scope
print(dir(d))

# Python3 program to demonstrate working


# of dir(), when user defined objects are passed are parameters.

# Creation of a simple class with __dir()__ method


class Supermarket:

# Function __dir()___ which list all the base attributes to be used.


def __dir__(self):
return['customer_name', 'product','quantity', 'price', 'date']

# user-defined object of class supermarket


my_cart = Supermarket()

# listing out the dir() method


print(dir(my_cart))

reload()

The reload() function allows you to reload a module that has been previously imported. This can be useful
during development when you want to test changes to a module without restarting your Python
environment.

import importlib

importlib.reload(module_name)

Unloading a Python module is not possible in Python yet.

Packages in Python

We usually organize our files in different folders and subfolders based on some criteria, so that they can be
managed easily and efficiently. For example, we keep all our games in a Games folder and we can even
subcategorize according to the genre of the game or something like this.

Packages are a way of organizing related modules into a single directory hierarchy. They allow for a better
organization of modules and avoid naming collisions. Packages are essentially directories with a special
__init__.py file, which can be empty or can contain initialization code for the package.

Modules and packages are fundamental concepts in Python programming. They help in organizing and
reusing code effectively, making your projects more manageable and maintainable. Understanding how to
use and create modules and packages will greatly enhance your proficiency in Python development.

10 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

Creating Package

Let’s create a package in Python named mypckg that will contain two modules mod1 and mod2. To create
this module follow the below steps:

• Create a folder named mypckg.


• Inside this folder create an empty Python file i.e. __init__.py
• Then create two modules mod1 and mod2 in this folder.

Mod1.py

def abc():
print("Welcome to abc")

Mod2.py

def sum(a, b):


return a+b

__init__.py helps the Python interpreter recognize the folder as a package. It also specifies the resources to
be imported from the modules. If the __init__.py is empty this means that all the functions of the modules
will be imported. We can also specify the functions from each module to be made available.

For example, we can also create the __init__.py file for the above module as:

__init__.py

from .mod1 import abc


from .mod2 import sum

This __init__.py will only allow the abc and sum functions from the mod1 and mod2 modules to be imported.

Import Modules from a Package

We can import these Python modules using the from…import statement and the dot(.) operator.

Syntax:

import package_name.module_name
Example 1:

from mypckg import mod1


from mypckg import mod2

mod1.abc()
res = mod2.sum(1, 2)
print(res)

Example 2:

11 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

from mypckg.mod1 import abc


from mypckg.mod2 import sum
gfg()
res = sum(1, 2)
print(res)
Python File Handling

File handling is an essential aspect of programming, allowing you to interact with files on your system.
Python provides a straightforward way to perform various operations on files, including opening, reading,
writing, renaming, deleting, and managing directories.

The concept of file handling has stretched over various other languages, but the implementation is either
complicated or lengthy, but like other concepts of Python, this concept here is also easy and short. Python
provides inbuilt functions for creating, writing and reading files. There are two types of files that can be
handled in python, normal text files and binary files (written in binary language, 0s and 1s).

• Text files: In this type of file, Each line of text is terminated with a special character called EOL (End
of Line), which is the new line character (‘\n’) in python by default.
• Binary files: In this type of file, there is no terminator for a line and the data is stored after
converting it into machine-understandable binary language.

Advantages of File Handling

Versatility: File handling in Python allows you to perform a wide range of operations, such as creating,
reading, writing, appending, renaming, and deleting files.

Flexibility: File handling in Python is highly flexible, as it allows you to work with different file types (e.g.
text files, binary files, etc.), and to perform different operations on files (e.g. read, write, append, etc.).

User–friendly: Python provides a user-friendly interface for file handling, making it easy to create, read,
and manipulate files.

Cross-platform: Python file-handling functions work across different platforms (e.g. Windows, Mac,
Linux), allowing for seamless integration and compatibility.

1. Opening and Closing Files


Before performing any operation on the file like reading or writing, first, we have to open that file. For this,
we should use Python’s inbuilt function open() but at the time of opening, we have to specify the mode,
which represents the purpose of the opening file.

open(filename, mode): Opens a file in a specified mode (read, write, etc.).

close(): Closes an open file, saving any unsaved changes.

f = open(filename, mode)

Where the following mode is supported:

r: open an existing file for a read operation.

w: open an existing file for a write operation. If the file already contains some data then it will be
overridden but if the file is not present then it creates the file as well.

a: open an existing file for append operation. It won’t override existing data.

12 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

r+: To read and write data into the file. The previous data in the file will be overridden.

w+: To write and read data. It will override existing data.

a+: To append and read data from the file. It won’t override existing data.

Example

# Open the file "MyFile1.txt" (same directory) in read mode and store its reference in the variable file1

file1 = open("MyFile.txt", "r")

# Open the file "MyFile2.txt" (from D:\Text) in write mode and store its reference in the variable file2

file2 = open("D:\Text\MyFile2.txt", "w+")

#To close those files

file1.close()

file2.close()

2. Reading from Files (Working in read mode)

read(): Reads the entire content of a file.

readline(): Reads a single line from the file.

readlines(): Reads all lines and returns them as a list.

There is more than one way to read a file in Python. Let us see how we can read the content of a file in read
mode.

Example 1: The open command will open the file in the read mode and the for loop will print each line
present in the file.

# a text file named "myfile", will be opened with the reading mode.

file = open('myfile.txt', 'r')

# This will print every line one by one in the file

for each in file:

print (each)

Example 2: In this example, we will extract a string that contains all characters in the file then we can
use file.read().

# Python code to illustrate read() mode

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

print (file.read())

Example 3: Another way to read a file is to call a certain number of characters like in the following code the
interpreter will read the first five characters of stored data and return it as a string:

13 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

# Python code to illustrate read() mode character wise

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

print (file.read(5))

Example 4: In this example, we will see how we can read a file using the with statement.
The with statement is a replacement for commonly used try/finally error-handling statements. A common
example of using the with statement is opening a file. To open and read a file in Python:

# Python code to illustrate with()

with open("myfile.txt") as file:

data = file.read()

print(data)

The with statement automatically closes the file after you’ve completed writing it.

Example 5:

We can also split lines while reading files in Python. The split() function splits the variable when space is
encountered. You can also split using any characters as you wish.

# Python code to illustrate split() function

with open("myfile.txt", "r") as file:

data = file.readlines()

for line in data:

word = line.split()

print (word)

3. Writing to Files

There are two ways to write in a file.

write() : Inserts the string str1 in a single line in the text file.

File_object.write(str1)

writelines() : For a list of string elements, each string is inserted in the text file. Used to insert multiple
strings at a single time.

File_object.writelines(L) for L = [str1, str2, str3]

Example

# Python program to demonstrate writing to file


file1 = open('myfile.txt', 'w')
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
s = "Hello\n"
file1.write(s) # Writing a string to file

14 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

file1.writelines(L) # Writing multiple strings at a time


file1.close() # Closing file
# Checking if the data is written to file or not
file1 = open('myfile.txt', 'r')
print(file1.read())
file1.close()
5. Renaming and Deleting Files

os.rename(current_file_name, new_file_name): Renames a file.

Python os module provides methods that help you perform file-processing operations, such as renaming
and deleting files. To use this module you need to import it first and then you can call any related functions.

The rename() method takes two arguments, the current filename and the new filename.

Syntax : os.rename(current_file_name, new_file_name)

# Rename a file from name1.txt to name2.txt

import os

os.rename( "name1.txt", "name2.txt" )

os.remove(file_name): Deletes a file.

You can use the remove() method to delete files by supplying the name of the file to be deleted as the
argument.

Syntax : os.remove(file_name)

Following is the example to delete an existing file name2.txt −

import os

os.remove("name2.txt") # Delete file name2.txt

Directories are a way of storing, organizing, and separating the files on a computer. The directory that does
not have a parent is called a root directory. The way to reach the file is called the path. The path contains
a combination of directory names, folder names separated by slashes and colon and this gives the route to
a file in the system.

Creating new directory:

• os.mkdir(name) method to create a new directory.


• The desired name for the new directory is passed as the parameter.
• By default it creates the new directory in the current working directory.
• If the new directory has to be created somewhere else then that path has to be specified and the
path should contain forward slashes instead of backward ones.

Getting Current Working Directory (CWD):

• os.getcwd() can be used.


• It returns a string that represents the path of the current working directory.
• os.getcwdb() can also be used but it returns a byte string that represents the current working
directory.

15 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]

• Both methods do not require any parameters to be passed.

Changing Current Working Directory (CWD):

• Every process in the computer system will have a directory associated with it, which is known as
Current Working Directory(CWD).
• os.chdir() method is used to change it.
• The parameter passed is the path/name of the desired directory to which one wish to shift.

Renaming a directory:

• os.rename() method is used to rename the directory.


• The parameters passed are old_name followed by new_name.
• If a directory already exists with the new_name passed, OSError will be raised in case of both Unix
and Windows.
• If a file already exists with the new_name, in Unix no error arises, the directory will be renamed.
But in Windows the renaming won’t happen and error will be raised.
• os.renames(‘old_name’,’dest_dir:/new_name’) method works similar to os.rename() but it
moves the renamed file to the specified destination directory(dest_dir).

Removing a directory

• os.rmdir() method is used to remove/delete a directory.


• The parameter passed is the path to that directory.
• It deletes the directory if and only if it is empty, otherwise raises an OSError.

Example: Reading and Writing a File

# Opening a file in write mode

file = open("example.txt", "w")

# Writing to the file

file.write("Hello, this is a sample text.\n")

file.write("This is another line.\n")

# Closing the file

file.close()

# Opening the file in read mode

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

# Reading the contents

content = file.read()

print(content)

# Closing the file

file.close()

16 Naipunnya School of Management, Cherthala [Jithin Babu]

You might also like