0% found this document useful (0 votes)
68 views19 pages

PSPP Unit-5

The document is a course material for a B.Tech program focusing on Problem Solving and Python Programming, specifically covering Files, Modules, and Packages. It details file operations, error handling, and the structure of Python modules and packages, including examples and coding exercises. Additionally, it explains exception handling mechanisms and provides a guide on creating and using Python packages.

Uploaded by

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

PSPP Unit-5

The document is a course material for a B.Tech program focusing on Problem Solving and Python Programming, specifically covering Files, Modules, and Packages. It details file operations, error handling, and the structure of Python modules and packages, including examples and coding exercises. Additionally, it explains exception handling mechanisms and provides a guide on creating and using Python packages.

Uploaded by

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

ST.

JOSEPH’S COLLEGE OF Aunit of DMI


FoundationTrust Run By DMI Sisters
ENGINEERING AND TECHNOLOGY A.S.Nagar,Elupatti,Thanjavur-613 403

GE3151
PROBLEM SOLVING AND
PYTHON PROGRAMMING

B.TECH
I YEAR – I SEM
(2024-2025)

UNIT – 5
FILES,MODULES,PACKAGES

Presented
By
Asst.prof.A.Charmil
a
UNIT – V
FILES,MODULES,PACKAGES

FILES

1.FILE AND ITS OPERATION


 File is a collection of record.
 A file stores related data,information,settings or
commands in secondary storage device like magnetic
disk,magnetic tape,optical disl,flash memory.
File Type:
1.Text File
2.Binary File

Text File Binary File


Text File is a sequence of A Binary File store the data in
characters that can be the binary format.
sequentially processed by a (i.e,0’s and 1’s)
computer in forward direction.

Each line is terminated with a It contains any type of data


special character called the (pdf,images,word
(EOL) End Of the Line doc,spreadsheet,zip files,etc…)
character.
Mode In File:
Module Description
r Read only
w Mode write
a Only appending
r+ Read and write only

Differentiate write and append mode:


Write Mode Append Mode
 It is used to write a string  It is used to append (add)
in a file. a string in a file.
 If file is exist in the  It will add the string at
specified name,the the end of the old file.
existing content will
overwrite in a file by the
given string.

File Operation:
 Open a file
 Reading a file
 Writing a file
 Closing a file

1.Open ( ) function:
 Python built in open function to get a file object.
 The open function opens a file.
 It returns a something called a file object.
 File objects can turn methods and attributes that can be
used to collect.
Syntax:
file_object=open(“file_name”,”mode”)
Example:
fp=open=open(“text.txt”,”r”)
Create a text file:
fp=open(“text.txt”,”w”)

2.Read ( ) Function:
The different methods of read functions are,
 Read( ) - return one big string
 Readline( ) - return one line at a time
 Readlines( ) - return a list of lines
 Read line-by-line – return iterating in for loop
Syntax:
file_name.read ( )
Example:
fp=open(“a.txt”,”w”)
Print(fp.read())
Print(fp.read(6))
Print(fp.readline())
Print(fp.readline(3))
Print(fp.read())

Output:
a.txt

A file stores related


data,information,settings or
commands in secondary storage
3.Write( ) function:
This method is used to add information or content to
existing file.
Syntax:
File_name.write( )
Example:
fp=open(“a.txt”,”w”)
fp.write(“this file is a.txt”)
fp.close()
Output:
a.txt

A file stores related data,information, settings or


commands in secondary storage device like
magnetic disk, magnetic tape, optical disk, flash
memory.

This file is a.txt to


Add more lines
4.Close ( ) function:
It is used to close the file.
Syntax:
File name.close()
Example:
fp=open(“a.txt”,”w”)
fp.write(“this file is a.txt”)
fp.write(“to add more lines”)
fp.close()

A Program for one file content copy into another file:

Coding:

Source=open(“a.txt”,”r”)
destination=open(“b.txt”,”w”)
for line in source:
destination.write(line)
source.close()
destination.close()

Output:
Input a.txt Output b.txt
A file stores data, A file stores data, information,
information,settings or settings or commands in
commands in secondary secondary storage device like
storage device like magnetic magnetic disk, magnetic tape,
disk, magnetic tape, optical optical disk, flash memory
disk, flash memory

A Program to count number of lines, words and


characters in a text file:

Coding:

fp=open(“a.txt”,”r”)
Line=0
Word=0
Character=0
For line in fp:
Words=line.split( )
Line=line+1
Word=word+len(words)
Character=Character+len(line)
print(“Number of line”,line)
print(“Number of words”,word)
print(“Number of character”,Character)
output:

Number
Numberofofline=5
line=5
Number
Numberofofwords=15
Words=15
Number
Number of of character=47
Characters=47

ERRORS AND EXECEPTION HANDLING:


I-Errors
 Error is a mistake in python. It is also referred as bug. They
are almost always the fault of the programmer.
 The process of finding and eliminating error is called
debugging.

Types of errors:
1. Syntax error or compile time error
2. Run time error
3. Logical error
1).Syntax errors:
 Syntax errors are the errors which are displayed when the
programmer do mistakes when writing a a program, when
a program has syntax error it will get executed .
 Leaving out a keyword
 Leaving out a symbol, such as colon, comma,
brackets
 Misspelling a keyword
 Incorrect identation
2).Runtime errors:
 If a programmar is syntatically correct-that is free of
syntax errors-it will be run by python interpreter
 However, the program may execute unexpectedly during
execution if it encounters a runtime error
 when a program has runtime error it will get executed but
it will not produce output
 Division by zero
 performing an operation on incompatible types
 Using an identifier which has not been defined
 Trying to access a file which doesn’t exit

3).Logical errors:
 Logical errors are the most difficult to fix
 They occur when the program runs without crashing but
produces incorrect result
 Using the wrong variable name
 Indenting a blocks to wrong level
 Using integer division instead of floating point
division
 Getting operator precendence wrong

II - EXCEPTIONS

Execptions:
 An exception is an error thet happends during execution of
a program. When that error occurs.
Exception Handling Mechanism:
1.try-except
2.try-multiple except
3.try-except-else
4.raise exception
5.try-except-finally

EXCEPTION HANDLING MECHANISM


1.Try- Except 2.Try-Mulitiple 3.Try-Except-Else 4.Raise 5.Try-Except-
Except statement Finally

 The try and  Exception type  The else part  The raise  A finally clause
except must be will be statement is always
statements are different for excecuted only allows the executed
used to handle except if the try block programmer to before leaving
runtime errors. statements. does not raise force a the try
the exception. specified statement,
exception to whether an
Output:1 Output:1 Output:1 Output: Output :1
Enter the value of Enter the value of Enter the value of An exception flew Enter the value of
X=10 X=10 X=10 by! Traceback X=10
Enter the value of Enter the value of Enter the value of (most recent call Enter the value of
Y=5 Y=5 Y=5 last): Y=5
sum of 10 and 5 = result = 2 File”<stdin>”,line Result = 2
15 1, in <module> excecuting finally
Division of 10 and NameError:HiThe clause
5=2 re
MODULES

Modules In Python:
 A python module is a file that consists of python definition
and statements. A module can define functions, classes
and variables.

 It allows us to logically arrange related code and makes


the code easier to understand and use.

1.Import statement

 An import statement is used to import python module in


some python source file.

Syntax:
import module 1, [module 2,[….module]]
Example:
>>>import math
>>>print 9math.pi)
3.14159265
2.Import with renaming:
Example:
>>>import math as a
>>>print(“The value of pi is”,a.pi)
The value of pi is 3.14159265
3.Import file name:

Coding:
import support
support.add (3,4)
support.add (3.5,4.7)
support.add (‘a’,’b’)
support.add (“yona”,”alex”)
support.add (‘fleming’)

Output:

The result is 7
The result is 8.2
The result is ab
The result is yonaalex
Welcome,fleming

4.from …….import statement:

 It allows us to import specific attributes from a


module into current namespace.
Syntax:
from modulename import name2 [,name2[,……nameN]]
from support import add
support.add (3,4)
support.add (3.5,4.7)
support.add (‘a’,’b’)
support.add (“yona”,”alex”)
support.add (‘fleming’)

Output:

The result is 7
The result is 8.2
The result is ab
The result is yonaalex
Welcome,fleming

5.OS Module:
 The OS module in python provide function for
interacting with operating sysytem.

 To access the OS module have to import the OS


module in our program.

6.Sys Module:
 Sys module provides information about constant,
function and methods.
 It provides acess to some variables used or
maintained by the interpreter.
Steps to create the own module:
 Here we are going to create a calc module; our module
contains four functions

i.e add(), Sub(), Mul(), Div()

Program for calculator Output


module
Module name ;calc.py import calculator
def add(a,b); calculator.add(2,3)
print(a+b)
def sub(a,b);
print(a-b)
def mul(a,b);
print(a*b)
def div(a,b); Outcome
print(a/b) >>>5

PACKAGES

PACKAGES IN PYTHON:
 A Pacakage is a way of collecting related modules together
within a single treee like hierarchy.
 It has a well organized hierarchy for easier access.
 The directory can contain sub direction and files were as a
python package can have sub packages and modules.
 A package must contain a file named_init_.py in order for
python to consider it as a package.
 This file can be left empty.

TO CREATE PYTHON PACKAGE:

 Create a directory and name it with a package name.


 Keep sub directories ( sub packages ) and modules in
it.
 Create _init_.py file in the directory.
 The _init_.py file can be left empty but generally
place the initialization code with import statements
to import resources from a newly created package.

EX:
STEPS TO CREATE A PYTHON PACKAGE:

Step 1 :Create a packages directory.


Step 2 :Write module for calculator directory and save the
module in calculator directory.
Step 3 :Add the _init_.py file in the calculator directory.
Step 4 :To test your package import calculator package by
using sys.path.append().
THANK
YOU

You might also like