Unit 5
Unit 5
Part-A
• A module allows you to logically organize your Python code. Grouping related code into a module
makes the code easier to understand and use. A module is a Python object with arbitrarily named
attributes that you can bind and reference.
• Simply, a module is a file consisting of Python code. A module can define functions, classes and
variables. A module can also include runnable code.
2.Write a Python script to display the current date and time.(JAN-18)
5. How do you handle the exception inside a program when you try to open a non-existent file?
(Apr/May-2022)
filename = raw_input('Enter a file name: ')
try:
f = open (filename, "r")
except IOError:
print 'There is no file named', filename
6. How does try and execute work? (Nov/Dec-2022)
The try statement executes the statements in the first block. If no exception occurs, then except
statement is ignored. If an exception of type IO Error occurs, it executes the statements in the except
branch and then continues.
7. What is a pickle? (Nov/Dec-2022)
Pickling saves an object to a file for later retrieval. The pickle module helps to translate almost any
type of object to a string suitable for storage in a database and then translate the strings back in to
objects.
8. What is the use of the format operator? (Nov/Dec-2023)
The format operator % takes a format string and a tuple of expressions and yields a string that
includes the expressions, formatted according to the format string.
9. Write a note on modular design.(JAN-18)
A module is simply a file that defines one or more related functions grouped together. To reuse the
functions of a given module, we need to import the module.
Syntax: import <modulename>
10. Give differences between packages and modules in Python? (Nov/Dec-21)
Module Package
It can be a simple Python file (.py A Package is a collection of different
extensions)that contains collections of modules with an _init_.py file.
functions and global
variables.
Code organization Code distribution and reuse
Code within a single file Related modules in a directory hierarchy
None Multiple sub-modules and sub-packages
Only Python File(.py format) ‘_init_.py’ file and python files
import module_name import package_name.module_name
15. Write a python program to count words in a sentence using spilt() function. (Apr/May-2022)
countOfWords = len("Geeksforgeeks is best Computer Science Portal".split())
print("Count of Words in the given Sentence:", countOfWords)
Files:
• File is a named location on disk to store related information.
• There are two types of files:
• Text File
• Binary
Text File are sequence of lines, where each line includes a sequence a sequence of characters.
Each line is terminated with a special character, called EOL or End Of Line character.
Binary files is any type of file other than a text file.
OPENING A FILE
Example.py
fn=open('D:/ex.txt','r')
Reading A File
This method helps to just view the content of given input file.
Syntax: file variable=open(“filename”,‟r‟)
Syntax:
print(f.tell())
f.seek(5)
readline()
This method is used to read a single line from the input file.
It doesn‟t takes any argument.
Syntax:
f.readline()
readlines()
This method is used to read and display all the lines from the input file.
Syntax:
f.readlines()
File Object Attributes
Once a file is opened and you have one file object, you can get various information related to that
file.
Here is a list of all attributes related to file object:
Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, true otherwise.
Example.py
file=open('D:/ex.txt','wb')
print(file.name)
print(file.closed)
print(file.mode)
Output:
D:/ex.txt
False
Wb
Handle
This is used to manipulate the file.
If file open is successful, then OS returns a file handle.
Example.py
fn=open('D:/e.txt','w')
print(fn)
Output:
<_io.TextIOWrapper name='D:/e.txt' mode='w' encoding='cp1252'>
Writing A File
Without using methods:
write()
The write method puts data into the file.
The write() method writes any string to an open file. The write() method does not add a newline
character ('\n') to the end of the string –
Syntax : filevariable.write(string)
Here, passed parameter is the content to be written into the opened file.
>>> line1 = "This here's the wattle,\n"
f.write(line1)
Again, the file object keeps track of where it is, so if we call write again, it adds the new data to the
end.
>>> line2 = "the emblem of our land.\n"
>>> f.write(line2)
writelines()
The writelines method puts multiple data into the file.
The writelines() method writes any string to an open file.
Syntax : filevariable.writelines(string)
Example.py
f=open('D:/ex.txt','w')
f1=[„This is my book \n‟,‟I found it here‟]
f.writelines(f1)
f.close()
Output:
This is my book
I found it here
CLOSING A FILE
close():
The close() method of a file object flushes any unwritten information and closes the file object,
after which no more writing can be done.
Syntax :filevariable.close()
Example.py
# Open a file
f = open("input.txt", "wb")
print("Name of the file: ", f.name)
# Close opend file
f.close()
Output:
Name of the file: input.txt
input.txt
Welcome to world of robotics
This will be interesting
Output:
Welcome to world of robotics
This will be interesting
Welcome to world of robotics
This will be interesting
This is the end
File methods (Also study programs from file open,read,write & close)
No Methods with Description
1 Close the file .A closed file cannot be read or written anymore.
2 file.flush()-Flush the internal buffer,like stdio's fflush. This may be a no-op
on some file
3 file.fileno()-Returns the integer file descript or that is used by the underlying
implementation to request I/O operations from the operating system
4 file.isatty()-Returns True if the file is connected to atty(-like)device, else
False
5 file.read([size])-Reads atmost size bytes from the file(less if the read hits
EOF before obtaining size bytes).
6 file.readline([size])Reads one entire line from the file.A trailing newline
character is kept in the string.
7 file.seek(offset[,whence])Sets the file's current position
8 file.tell() Returns the file's current position
9 file.truncate([size])
2. Appraise the use of try block and except block in Python with syntax.(JAN-18)
EXCEPTION:
• An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a situation that
it cannot cope with, it raises an exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits
Errors
• Syntax error
• Indentation error
• Index error
• Name error
• Logical error
Output:
Invalid Syntax
Output:
Expected indent block (line 2)
Output:
print(a[10])
IndexError: list index out of range
`
Example.py (Name error)
x=10
print(X)
Output:
print(X)
NameError: name 'X' is not defined
Example.py (Logical error)
i=0
while i<5:
print(i)
i=i+1
Output:
0
0
0 (infinite loop,since i=i+1 is placed outside while loop)
Syntax :
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
We cannot use else clause as well along with a finally clause.
Example.py(divide by 0)
try:
x=10/0
print("Never executed")
except:
print("this is an error message")
Output:
this is an error message
Example.py (finally)
try:
f=open("D:/input.txt","r")
x=f.read()
except IOError:
print("Cannot find the file")
except:
print("Some other error")
else:
print("Contents of file",x)
finally:
f.close()
print("File closed")
Output:1
Contents of file
Welcome to world of robotics
This will be intresting
This is the end
File closed
Output:2
Cannot find the file
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the standard built-in
exceptions.
PACKAGES:
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and sub packages and so on.
It is a collection of many modules under a common name.
Python Packages are a way to organize and structure your Python code into reusable components.
Add Modules: Within the package directory, you can add Python files (modules) containing your
code.
Each module should represent a distinct functionality or component of your package.
Init File: Include an __init__.py file in the package directory. This file can be empty or can contain
an initialization code for your package. It signals to Python that the directory should be treated as a
package.
Subpackages: You can create sub-packages within your package by adding additional directories
containing modules, along with their own __init__.py files.
Importing: To use modules from your package, import them into your Python scripts using dot
notation. For example, if you have a module named module1.py inside a package named mypackage,
you would import its function like this: from mypackage.module1 import greet.
Distribution: If you want to distribute your package for others to use, you can create a setup.py file
using Python’s setuptools library. This file defines metadata about your package and specifies how it
should be installed.
Here’s a basic code sample demonstrating how to create a simple Python package:
From data manipulation to machine learning and visualization, these tools offer powerful capabilities
for analyzing data effectively.
NumPy
Pandas
SciPy
XGBoost
StatsModels
Yellowbrick
Arch
Dask-ML