0% found this document useful (0 votes)
72 views3 pages

UNIT V Hint

This document discusses files, modules, packages, and exceptions in Python. It covers key topics such as: 1. The different types of files in Python (text files, binary files), basic file operations (opening, reading, writing, closing files), and advantages of using files. 2. How to open, read from, write to, and close both text and binary files in Python using methods like open(), read(), write(), close(). 3. Exceptions in Python like ZeroDivisionError, IndexError, TypeError that can occur at runtime and how to handle them using try/except blocks.

Uploaded by

vengai
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)
72 views3 pages

UNIT V Hint

This document discusses files, modules, packages, and exceptions in Python. It covers key topics such as: 1. The different types of files in Python (text files, binary files), basic file operations (opening, reading, writing, closing files), and advantages of using files. 2. How to open, read from, write to, and close both text and binary files in Python using methods like open(), read(), write(), close(). 3. Exceptions in Python like ZeroDivisionError, IndexError, TypeError that can occur at runtime and how to handle them using try/except blocks.

Uploaded by

vengai
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/ 3

UNIT V - FILES, MODULES, PACKAGES

1. Files and exception:


File is a collection of related information to store permanently in the secondary memory. Such as hard disk, CD.
Each file is identified by a unique name. A named collection of files is called folder or directory.
Types of file: 1. Text file – Store the data in the form of characters and whitespaces
2. Binary file – Stored data in the form of bytes (images are converted in to bytes)
Advantages of files: 1. Data is stored in a file permanently. 2. Possible to update the data in future.
3. Huge amount of data also store. 4. Files are portable and easily copied.
2. Text files – A text file is a collection of sequence characters and whitespaces to store permanently in the secondary
memory. Such as hard disk, floppy disk, flash memory or compact disk. Each file is identified by a unique name.
3. File operations:
1. Opening a file : open( ) Eg: f1=open(“abc.txt”,”r”)
2. Reading from a file : read( ) Eg: f1=open(“abc.txt”,”r”); f1.read( )
3. Writing to a file : write( ) Eg: f1=open(“abc.txt”,”w”); f1.write(“hello”)
4. Appending to a file : write( ) Eg: f1=open(“abc.txt”,”a”); f1.write(“hello”)
5. Closing a file : close( ) Eg: f1.close( )
6. Removing a file : remove( ) Eg: os.remove(filename)
7. Renaming the file : rename( ) Eg: os.rename(old filename, new filename)
8. File positions : tell( ) Eg: position=f1.tell( )
9. Find positions : seek( ) Eg: f1.seek(offset,anwhere); f1.seek(10,5)
Opening a file
open( ) – Before read and write in the file you should open the file using open( ) built in function. ‘r’ – Default mode
Syntax to open a file : fileobject=open(“filename”,”access mode”,buffering)
Example : f1=open(“abc.txt”,”r”)
r reading only text file w writing only text file a appending text file
rb reading only binary file wb writing only binary file ab appending binary file
File opening methods
r+ both reading & writing w+ overwrites the text file a+ appending & reading
rb+ both r/w in binary file wb+ overwrites the binary file ab+ append&read binary
File object attributes: 1. fileobject.closed 2. fileobject.mode 3. fileobject.name

Closing a file
close( ) – At the end of the program the opened file should be closed using close( ) built in function.
Syntax to close a file : fileobject.close( )
Example : f1.close( )

4. Writing to a file - To write into a file, it is needed to open a file with access modes like ‘w’,’wb’,’w+’,’wb+’,’a’,’ab’,’a+’,’ab+’
write( ) – Writing a string or sequence of bytes (for binary files) is using write( ) method.
Syntax to write a file : fileobject.write(string)
abc.txt file
Example : f1=open(“abc.txt”,”w”) python programming
str=”python programming”
f1.write(str)
f1.close( )
Reading from a file - To read from a file, it is needed to open a file with access modes like ‘r,’rb’,’r+’,’rb+’
(i) Reading a file using read(size) method – Read all the lines of the text file & displays them line by line
Syntax to read a file : fileobject.read(size)
Example : f1=open(“abc.txt”,”r”) abc.txt file input output
str=f1.read( 7) python programming programming
problem solving problem solving
print(str) analysis and design analysis and design
f1.close( )
(ii) Reading a file using readline( ) method – Read all the lines in to list and displays with “\n” newline character
Syntax to read a file : fileobject.readline( )
Example : f1=open(“abc.txt”,”r”) abc.txt file input output
str=f1.readline( ) python programming [‘python programming\n’,‘problem
problem solving solving\n’,’analysis and design\n’]
print(str) analysis and design
f1.close( )
(iii) Reading a file using for loop – A file can be read line-by-line at a time using for loop
Syntax to read a file : for iterating_var in fileobject:
abc.txt file input output
Example : f1=open(“abc.txt”,”r”) python programming python programming
for line in f1: problem solving problem solving
print(line, end=” “) analysis and design analysis and design
f1.close( )
A Python program to count number of lines, words & characters in a text file
import os,sys
fname=input(“Enter file name”) abc.txt file input
if(os.path.isfile(fname)): python programming
f1=open(“fname”,”r”) problem solving
else: analysis and design
print(fname+”does not exist”)
sys.exit( )
Output
cl=cw=cc=0 Enter file name abc.txt
for line in f1: Number of lines: 3
words=line.split( ) Number of words: 7
cl=cl+1 Number of characters : 55
cw=cw+len(words)
cc=cc+len(line)
print(“Number of lines: %d Number of words: %d Number of characters : %d” %(cl,cw,cc))
f1.close( )
A Python program for copying a file
f1=open(“oldfile.txt”,”r”) oldfile input newfile input
f2=open(“newfile.txt”,”w”) python programming python programming
str=f1.read( ) problem solving problem solving
f2.write(str) analysis and design analysis and design
fl.close( )
5. Format operator – 1. Format operator is an operator ( % ), that takes a format string. 2. The argument of write should to
be a string. To put other values in a file, they have to be converted to strings
%d – Formatted to an integer, %g – Formatted to a floating-point integer, %s – Formatted to a string
Eg: apple=15; print("I have %d apple in my pocket" %apple) Output : I have 15 apple in my pocket
Eg: print("In %d years I have spotted %g %s" %(2,0.5,'parrot')) Output : In 2 years I have spotted 0.5 parrot
6. Command line arguments – Another method of input statements is uses command line arguments. It can be processed
by using sys module. Multiply all the values given to the function as parameter
sys.argv is the list of command line arguments. def mulitplyall(*values)
len(sys.argv) is the number of command line arguments. mul=1
*args – It will give us all the function parameters in the form of a list print(values)
**kwargs – It will give us all the keyword arguments for i in values:
import sys mul=mul*i
a=int(sys.srgv[1]) output print(“The multiplication of 5 X 2 is “, mul)
b=int(sys.argv[2]) python add.py 5 10 multiplyall(5,2)
c=a+b 15
print(c) Output The multiplication of 5 X 2 is 10

7. Errors: Errors are bugs occurred may be compile time or run time.
Types of Errors
Syntax error- Error occurs at Compile Time [keyword named as variable,indent,bracket missing,colon missing]
Logical error- Error occurs at Run Time [division by zero, index out of range, data type conversion]
Semantic error- Error occurs at producing output [unwanted output]
8. Exceptions: Exceptions are unexpected events that occur during the execution of program. An error occurs at runtime
Types of Exceptions at run time
ZeroDivisionError Eg: print(55/0)
IndexError Eg: a = [ ]; print(a[5])
TypeError Eg: tup = ("a", "b", "d", "d"); tup[2] = "c"
FileNotFoundError Eg: try: f = open(filename, "r"); except FileNotFoundError: print("There is no file", filename)
ValueError Eg: number = float(user_input) ; except ValueError:
IOError Eg: : try: f = open(filename, "w"); except IOError: print("Access Denied”)
9. Handling exceptions : To prevent an exception from causing our program to crash, by wrapping the block of code in a
try ... except construct. Raising our own exceptions to detects an error using raise keyword.
try:
print(55/0) # Try do do something that could fail.
except ZeroDivisionError:
print(“Divide by zero error”)# This will be executed if a ``ValueError`` is raised. Multiple except may allowed.
except ValueError:
print(“Value Error”)
else:
print(“No Error”) # This will be executed if not exception got raised in the `try`` statement.
finally: # This block is to ensure that code is always executed
print(“Error may raised or not”) # This will be executed whether or not an exception is raised.
10. Modules - A module is a file containing Python definitions and statements. The filename is the module name with the
suffix.py appended. Inbuilt modules are stored in standard python library like import math, import string, import time
Example inbuilt math module: The math module contains the kinds of mathematical functions like sqrt,sin,cos,log..
Namespaces : A namespace is a collection of identifiers that belong to a module, or to a function.
Scopes: The scope of an identifier is the region of program code in which the identifier can be accessed, or used.
There are three important scopes in Python:
Local scope refers to identifiers declared within a function.
Global scope refers to all the identifiers declared within the current module, or file.
Built-in scope refers to all the identifiers built into Python
import statement - A statement which makes the objects contained in a module available for use within another module.
Here are three different ways to import names into the current namespace, and to use them:

The import statement Syntax import math


import module1,module2,…module n x=math.sqrt(10); print(x)

The from…import statement Syntax from math import cos, sin, sqrt
from module import functioname1,name2,..name n x = sqrt(10); print(x)

The from…import * statement Syntax from math import *


from module import * x = sqrt(10); print(x)

Import with renaming Syntax import math as a


Import oldmodulename as newmodulename x=a.sqrt(10); print(x)

Creating your own modules / User defined modules


All we need to do to create our own modules is to save our script as a file with a .py extension.
arithmetic.py import arithmetic *
def add(a,b): a=int(input(“Enter 1st number to add”)
c=a+b b=int(input(“Enter 2nd number to add”)
print(“Addition of two number is:”, c) arithmetic.add(a,b)

11. Packages: A package is a directory it has collection of Python modules. Multiple modules in the same directory.
Having a directory of modules allows us to have modules contained within another module. This allows us to use qualified
module names, clarifying the organization of our software.
Directory structure: D:\python\mathematicalprocess\arithmetic.py
D:\python\mathematicalprocess\logical.py

You might also like