0% found this document useful (0 votes)
32 views59 pages

Unit V

This document covers the concepts of files, modules, and packages in Python, including file types, handling exceptions, and using modules. It explains how to read and write files, manage errors, and create packages with modules. Illustrative programs demonstrate practical applications such as word counting, file copying, and validation checks.

Uploaded by

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

Unit V

This document covers the concepts of files, modules, and packages in Python, including file types, handling exceptions, and using modules. It explains how to read and write files, manage errors, and create packages with modules. Illustrative programs demonstrate practical applications such as word counting, file copying, and validation checks.

Uploaded by

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

UNIT V FILES, MODULES, PACKAGES

Files and exceptions: text files, reading and writing files, format
operator; command line arguments, errors and exceptions,
handling exceptions, modules, packages; Illustrative programs:
word count, copy file, Voter’s age validation, Marks range
validation (0-100).
FILE-INTRODUCTION
• A file is a collection of data stored on a secondary storage device like hard disk.

• File is a named location on disk to store related information. It is used to permanently

store data in a non-volatile memory (e.g. hard disk).

• When a program is being executed,its data is stored in random access memory(RAM).

• Since, random access memory (RAM) is volatile which loses its data when computer is

turned off,if you want to use the data in future,then you need to store this data on a

permanent or non-volatile storage media such as hard disk,USB drive,DVD etc,.

• Data on non-volatile storage media is stored in named locations on the media is called

file.
FILE PATH
• Most file systems that are used today store files in a tree(hierarchial
structure).
C:\

TEACHERS STUDENTS STAFFS

UG PG

BTECH
• Where C:\ -- ROOT NODE OR ROOT FOLDER
• Teachers,Students &Staffs --- folders
• UG &PG– subfolders
Relative path :
A relative path describes the location of a file relative to the current
(working) directory*.
Under UG->BTECH
Absolute path :
An absolute path describes the location from the root directory.
C:\STUDENTS\UG\BTECH
TYPES OF FILES
• Python supports two types of files
• Text file
• Binary file
Text file or ASCII Text Files:
• A text file is a sequences of characters that can be sequencially
processed by the computer.
• We can perform reading,writing or appending at any given time.
• Text file can process only characters.and it is human -readable
Binary file:
• Binary file are not human readable.
• It’s a file which may contains any type of data,encoded in binary form
for computer storage and processing purposes.
• It includes file such as word processing,documents,PDF’s,images,
spreadsheets,videos ,zip files and other executable files.
• Binary files stores the data in the internal representation format.
• An integer value will be stored in binary format as 2 byte value.
Opening and Closing files
1.Open() function:
• Before reading or writing to the file,you must first open it using python
open()function.

• Syntax:

• Fileobj=open(“filename”,accessmode)

• Here,
• File name is the name of the file you want to access
• Accessmode indicates the mode in which the file has to be
opened,i.e.,read,write,append etc.,
In the above statement, the file filename.txt is opened in append
and read modes.
That means we can read data from the file using the file object
named file.
File object attributes
2.close() function

• The close() method is used to close the file object.


• Once the file object is closed,we cant further read from or write in to
the file associated with the file object.
• Syntax:
fileobj.close()
Reading &Writing the files

• The read() and write() are used to read data from the file and write
data to file .
1.write() and writelines() methods:
• write()
• the write() method is used to write the string to an already opened
file.
• Syntax:
• Fileobj.write(“string”)
Program to write a message in
filename.txt
2.writelines() method

• The writelines() methods is used to write the list of strings .


Syntax:
Fileobj.writelines(lines)
Program to write the file using writelines() method
append() method:

• It is same as write() method.to append the file ,you must open it


using “a” or “ab” mode depending on the whether it s text file or
binary file.
• Program for append a data to an already existing file:
read() and readline() methods

• The read() and readline() method is used to read the string in the file.
• Syntax:
• Fileobj.read([count])
• Program to print the first 10 characters
readline() method
• The readline() is used to read the single line from the file.
Program to display the contents of a file
Opening file using “with”
keyword
Splitting words

• It splits the lines based on the character.


• By default,this character is space but you can even specify any other
character to split words in string.
Illustrative Program: Word Count
Illustrative Program:Copy file from one another
• Step 1: Copy the original file path
D:\GE3151 -PYTHON\python laboratory\1.docx
• Step 2:Copy the target file path
D:\GE3151 -PYTHON\3.docx
Step 3: Copy the file in Python using Shutil.copyfile
After copying
Illustrative Program: Copy file
from one another
• Open file1 in read mode
• Open file2 in write mode
• Read content from file1 as data
• Write data into file2
• Close file1
• Close file2
Illustrative Program: longest word

file = open("sample.txt","r")
data = file.read()
words = data.split()
maxlen = 0
for i in words:
if maxlen < len(i):
maxlen = len(i)

print("The length of longest word:" , maxlen)


Illustrative Program: longest word
Errors &Exceptions
• Errors are the problems in a program due to which the program will
stop the execution.
• On the other hand, exceptions are raised when some internal events
occur which changes the normal flow of the program.

• Two types of Error occurs in python.

Syntax errors
Logical errors (Exceptions)
Syntax Errors
• Syntax errors occurs whe we violate the rules of python and they are
the most common kind of error .
• For example ,consider the lines of codes given below:

• We missed the ‘:’ before the keyword print.


logical errors(Exception)

• The runtime error that occurs after passing the syntax test is called
exception or logical type.
• For example, when we divide any number by zero then the
ZeroDivisionError exception is raised, or when we import a module
that does not exist then ImportError is raised.
Handling Exceptions

• We can handle exceptions in our program by using try block and


except block.
• A critical operation which can raise exception is placed inside the try
block and the code that handles exception is written in except block.
• Syntax :
try
statements
except ExceptionName:
statements
Exception No Program executes
raised? normally

yes

No The program is
Handler
terminated and an
found?
error message is
displayed

yes

Program control is
transferred to handler
Program to handle the divide by zero exception
Built-in & user-defined exception
Multiple except blocks
• Syntax :
try:
operations are done in this block
Except Exception1
if there is Exception1 ,then execute this block
Except Exception2
if there is Exception2,then execute this block
else:
if there is no exception,then execute this block
Multiple exception in a single block
try……. finally block
Syntax:

try:
statements
finally:
always executed
Illustrative Program: Vote Validity
Illustrative Program :Student mark range validation
Modules
• Modules are pre-written piece of code that are used to perform
common tasks like generating random numbers,performing
mathematical operations.
• In simply,module is a file with a .py extension that has definitions of
all functions and variables that you would like to use in other
program.
Use a module

• The basic way to use a module is to add import module_name as the


first line of your program.
• Then writing module_name.var to access the functions and values
with the name var in the module.
Program to print the sys.path variable

• In the below code, we import the sys module(short form of system)


using the import statement to use its functionality related to the
python interpreter and its environment.
The from…..import statement
• A module may contain definition for many variables and functions.
• When you import module,we can use any variable or function defined
in that module.

• To import more than one item from a module,use comma separated


list.
Packages
• We can categorize and organize a large number of files in different
folders and subfolders based on some criteria so that we can find and
manage them easily.
• A package is actually a folder containing one or more module files.
• Modules can contain multiple objects such as classes,functions etc.
• A Package is a collection of one or more relevant modules.
• A Package is a hierarchical file directory structure where package
contains sub-packages,modules and submodules.
• Every package in python is a directory which must have a special file
called ___init__.py
• __init__.py : It is a Python file found in a package directory, it is
invoked when the package or a module in the package is imported.
Create Package

• For example: To create a package called “MyPackage”,having the


module “MyModule” and the __init__.py file.

• Import MyPackage.MyModule
(or)
• from MyPackage import MyModule
Step1: create __init__.py
&MyModule.py
Step 2: Create a file Sample.py

You might also like