0% found this document useful (0 votes)
39 views11 pages

Unit 5

The document covers various aspects of Python programming related to files, modules, and exception handling. It explains the concept of modules and packages, provides examples of file operations, and details how to handle exceptions using try and except blocks. Additionally, it discusses file modes, methods for reading and writing files, and common exceptions encountered in Python.

Uploaded by

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

Unit 5

The document covers various aspects of Python programming related to files, modules, and exception handling. It explains the concept of modules and packages, provides examples of file operations, and details how to handle exceptions using try and except blocks. Additionally, it discusses file modes, methods for reading and writing files, and common exceptions encountered in Python.

Uploaded by

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

UNIT-V FILES, MODULES, PACKAGES

Part-A

1. What is module? Give example.(Dec/Jan-2019)

• 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)

#import time module


import time
from time import gmtime, strftime
t = time.localtime()
print (time.asctime(t))
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()))
print(strftime("%A", gmtime()))
print(strftime("%D", gmtime()))
print(strftime("%B", gmtime()))
print(strftime("%y", gmtime()))
# Convert seconds into GMT date
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime(1234567890)))
3. What is an exception? List few common exception types.(Apr/May-2024)8.
Whenever a runtime error occurs, it creates an exception. The program stops execution and prints an
error message. For example, dividing by zero creates an exception:
print 55/0
ZeroDivisionError: integer division or modulo
Exception Types:

FloatingPointError Raised when a floating point operation fails.


GeneratorExit Raise when a generator's close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when the index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.

4. How the Exceptions are handled in Python? (Dec/Jan-2019)


In Python, exceptions are caught and handled using the 'try' and 'except' block. 'try' contains the code
segment which is susceptible to error, while 'except' is where the program should jump in case an
exception occurs. You can use multiple 'except' blocks for handling different types of exceptions.

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

11. How do you delete a file in Python?(Apr/May-2023)


The remove() method is used to delete the files by supplying the name of the file to be deleted as
argument.
Syntax: os.remove(filename)
12. How do you use command line arguments to give input to the program? (Apr/May-2023)
Python sys module provides access to any command-line arguments via sys.argv. sys.argv is the list
of command-line arguments. len(sys.argv) is the number of command-line arguments.
13. List any four file operations.(Apr/May-2022)
Method Description

Read() Returns the file content


Close() Close the file
Detach() Returns the separated raw stream from the buffer
Fileno() Returns a no.that represents the stream
Flush() Flushes the internal buffer

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)

# Quick One Line Codes


print(len("Geeksforgeeks is best Computer Science Portal".split()))

# Quick One Line Code with User Input


print(len(input("Enter Input:").split()))
PART-B
1.Tabulate the different modes for opening a file and explain the same.(JAN-18),(Nov/Dec-
2021),(Nov/Dec-2023)
Files and exception: text files, reading and writing files, format operator, command line arguments,
errors and exceptions, handling exceptions, modules, packages; Illustrative programs: word count,
copy file

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.

FILE OPERATIONS (4)


1. open()
2. read()
3. write()
4. close()

OPENING A FILE

The open Function


This function creates a file object, which would be utilized to call other support methods associated
with it.
Syntax
file object = open(“file_name” ,[mode])

Here are parameter details:


 file_name: The file_name argument is a string value that contains the name of the file that you
want to access.
 mode: The access_mode determines the mode in which the file has to be opened, i.e., read,
write,append, etc. A complete list of possible values is given below in the table.
This is optional parameter and the default file access mode is read (r).
 Here is a list of the different modes of opening a file
Modes Description:
r Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the
Beginning of the file. This is the default mode
r+ Opens a file for both reading and writing. The file pointer placed at the
Beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer
Placed at the beginning of the file.
W Opens a file for writing only. Overwrites the file if the file exists. If the file
Does not exist, creates a new file for writing.
Opens a file for writing only in binary format. Overwrites the file if the file
wb Exists. If the file does not exist, creates a new file for writing.
Opens a file for both writing and reading. Overwrites the existing file if the file
wb+ Exists .If the file does not exist, creates a new file for reading and writing.
Opens a file for appending. The file pointer is at the end of the file if the file
exists.Thatis,thefileisintheappendmode.Ifthefiledoesnotexist,itcreates a new file for
a writing
ab Creates a new file for reading and writing.
Opens a file for both appending and reading in binary format. The file pointer
Is at the end of the file if the file exists. The file opens in the append mode. If the file
ab+ does not exist, it creates a new file for reading and writing

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‟)

Methods used in reading a file


1. Size of data()
2. tell() and seek()
3. readline()
4. readlines()
5. File object attributes
6. Using loops
7. Handle
Size of Data: (using read())
 This read() specifies the size of data to be read from input file.
 If size not mentioned,it reads the entire file & cursor waits in last position of file.

Tell() & seek()


 Tell() method displays the current position of cursor from the input file.
 Seek() takes an argument,and moves the cursor to the specified position which is mentioned as
argument.

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

Example2.py (Counting lines in a file)


fn=open('D:/e.txt')
count=0
for i in fn:
count=count+1
print(count)
Output: 2

Example.py (If statement in for loop)


fn=open('D:/e.txt')
for i in fn:
if i.startswith('This'):
print(i)
Output:
This is a magic.
Example.py (prompt)
fn=input("enter the filename:")
a=open(fn)
count=0
for i in a:
if i.startswith('This'):
count=count+1
print(count)
Output:
enter the filename:D:/e.txt
1

Writing A File
Without using methods:

 To write a file, we have to open it with mode 'w' as a second parameter:


 Syntax: f.open(„filename‟,‟mode‟)
>>> f = open('output.txt', 'w')
>>> print(f)
<open file 'output.txt', mode 'w' at 0xb7eb2410>
 If the file already exists, opening it in write mode clears out the old data and starts fresh. If the file
doesn‟t exist, a new one is created.

Methods of writing a file:


1. write() – writes a single line into the specified file.
2. writelines() – writes multiple lines into the specified file.

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

Python program to implement all file read operations Example.py


#Opens the file newly
fn=open('D:/ex.txt','r')
#reads the entire data in file
print(fn.read())
#Moves the cursor to the specified position
fn.seek(4)
#Reads the data from the current cursor position after seek is done print(fn.read())
#Moves cursor to the first position
fn.seek(0)
#Reads the data in mentioned size
print(fn.read(4))
#Displays the current cursor position
print(fn.tell())
fn.seek(0)
#Reads all lines from the file
print(fn.readline())
fn.seek(0)
print(fn.readlines())
ex.txt
Welcome to the world of Robotics
Output:
Welcome to the world of Robotics
ome to the world of Robotics
Welc
4
Welcome to the world of Robotics
['Welcome to the world of Robotics']
Other file operations
example.py (renaming a file)
import os
os.rename('d:/e.txt','d:/e1.txt')
Output:
File is renamed.
Example.py(removing a file)
import os
os.remove('d:/e1.txt')
Output:
File will deleted from the specified path.
Example.py (append mode operation)
#contents of file before append mode
f=open("D:/input.txt","r")
print(f.read())
f.close()
#Open in append mode
s=open("D:/input.txt","a")
s.writelines("\nThis is the end")
s.close()
#Read file after writing.
f=open("D:/input.txt","r")
print(f.read())
f.close()

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

Example.py (Syntax error)


if x<10
print(X)

Output:
Invalid Syntax

Example.py (Indentation error)


if x<10:
print(X)

Output:
Expected indent block (line 2)

Example.py (Index error)


a=[1,2,3,4,5]
print(a[10])

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 (except statements


try:
a=int(input("Enter a :"))
b=int(input("Enter b:"))
print(a+b)
print(a/b)
except ArithmeticError:
print("Divide by 0")
Output:
Enter a :10
Enter b:0
10
Divide by 0

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.

3. Describe the concept of python Packages.(Nov/Dec-2023)

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.

How to Create Package in Python?


Creating packages in Python allows you to organize your code into reusable and manageable modules.

Here’s a brief overview of how to create packages:


 Create a Directory: Start by creating a directory (folder) for your package. This directory will serve
as the root of your package structure.

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:

1. Create a directory named mypackage.


2. Inside mypackage, create two Python files: module1.py and module2.py.
3. Create an __init__.py file inside mypackage (it can be empty).
4. Add some code to the modules.
5. Finally, demonstrate how to import and use the modules from the 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

You might also like