0% found this document useful (0 votes)
16 views6 pages

Unit 5

The document provides an overview of file handling, modules, and packages in Python, detailing the types of files, modes for opening files, and various file methods. It also discusses error handling, exceptions, and the use of modules and packages for organizing code. Additionally, it covers database operations and the process of pickling and unpickling objects for storage.

Uploaded by

senoj
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)
16 views6 pages

Unit 5

The document provides an overview of file handling, modules, and packages in Python, detailing the types of files, modes for opening files, and various file methods. It also discusses error handling, exceptions, and the use of modules and packages for organizing code. Additionally, it covers database operations and the process of pickling and unpickling objects for storage.

Uploaded by

senoj
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/ 6

UNIT-5 FILES, MODULES, PACKAGE

Files are of two type. Binary file and text file


Text file is a stream of character that end with a EOF marker. (end of file)
Binary file -any type of data encoded in binary form. Eg image file
When you want to read from or write to a file ,you need to open it. Once the reading/writing is
over it needs to be closed. So that, resources that are tied with the file are freed. Python has a
built-in function open() to open a file. This function returns a file object, also called a handle,
as it is used to read or modify the file accordingly.
f = open("sample.txt", “r”, encoding=’utf-8’) # open file in current directory
f = open('c:\pyprg\ch13sample5.csv') # specifying full path
f is file object. ‘r’ is the mode. "sample.txt" is the file name or path. Other modes are also
possible.
‘r’ Open a file for reading. (default)
‘w’ Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
‘x’ Open a file for exclusive creation. If the file already exists, the operation fails.
‘a’ Open for appending at the end of the file without truncating it. Creates a new file if it does
not exist.
‘t’ Open in text mode. (default)
‘b’ Open in binary mode
‘+’ Open a file for updating (reading and writing)

File attributes and methods


f.name
f.mode
f.closed

f.tell() Current position in a file


f.seek()

f.close() Free up the resources tied up with file

f.read() ‘hello\nworld’ #read till EOF. Return newline as \n.


f.read() “” #return empty string since already read.
f.read(4) ‘hell’ #read first four characters.
f.read(4) ‘o\nwo’ #read next four characters
f.readline() #read upto the next newline character including \n
f.readlines() # return a list of lines.

for line in f: # read line by line


print(line, end=’ ’)

f.write(‘hello world’)
11 (number of characters written)
f.writeline()
f.writelines(x) x is a list of strings

import os
os.rename(“text1.txt”,”text2.txt”)
os.remove(“text2.txt”)

seekable() return true if random access possible


f.seek(offset, from) can be from start, current, end.
readable()
writeable()

import os.path
os.path.isfile(“text1.txt”) return True if file exist

Format operators

% operator
x=52
k=’in %g years i have passed %d %s’%(3.5, x , ‘courses’)
print(k)

’in 3.5 years i have passed 52 courses’

%d integer
%u unsigned int
%c character
%s string
%f float
%o octal
%x, %X hexadecimal
%e, %E exponential form
%g shorter of %f and %e
%G shorter of %f and %E

print(‘%10f’%12.2346)
12.234600
print(‘%05d’%12)
00012
print(“%+10s”%“cat”) + means right align - for left align default is center align 10
is width
cat

Using format function

“{:*^8}”.format(“cat”)
**cat***
^ center > right default is left alignment
Here * is padding character. Center alignment. total width 8 character.

What is meant by command line arguments?


Arguments given along with file name on the command lines

import sys
print(len(sys.argv))
print(str(sys.argv))

save the program as test.py and run on command line

>>> test.py arg1 arg2 arg3


4
[test.py arg1 arg2 arg3] #first argument is script file name itself hence count is 4.

Errors

There are three types of errors


Syntax error: if a>b compile error #colon missing
Runtime error System hang. division by zero
Logical error program runs but wrong answer. Infinite loop etc

Exceptions
Errors detected during execution is called exceptions. Trying to open a file that does not exist,
Divide by Zero, Trying to import non existing module lead to exceptions.
Whatever be the error , python create a exception object. If not handled properly it prints a
traceback to the error along with some details about why the error occurred.

Builtin exceptions

IndexError out of range


KeyError key not found in dictionary
NameError variable not found
IndendationError
TypeError function applied on a object of wrong type
ZerodivisionError
ValueError
OverflowError
OSError
MemoryError
ImportError
Handling exceptions
When exception occur, it stops the current process and pass it to the calling process until it is
handled. If function A calls function B which inturn call function C. If an exception occur in
function C. if not handled by C exception will be passed to B. if not handled by B goes to A. If
never handles error messages will be produced and program suddenly halts.

try:
statement
except syntaxerror:
print(“syntax error”)
except zerodivisionerror:
print(“division by zero”)
except: #should be in the last
print(“some other error”)
else:
print(“no exception”)
finally:
print(“over”)

else and finally are optional. Finally block is used for doing concluding tasks like closing file
resources.

Raising exception
ex=runtimeerror(“wrong argument type”)
raise ex

Modules
User can write a .py file having the definitions of all the functions needed to perform common
tasks like mathematical operations. We can import this module in another program and access
variables and methods by using module_name.var. Module must be in the same directory as
that of program in which it is imported.it can be in one of the die=rectories listed under sys.path

example.py # module name


def add(a,b):
return a+b
import example
s=example.add(8, 9)
print(s)
>>> 17

from example import add


s=add(8,9) # No need to use module name
print(s)
>>> 17

math module
Contain builtin functions like
sqrt() sqrt(64) 8
floor() eg print(floor(3.87)) 3
ceil() eg print(ceil(3.17)) 4
Pi

From math import pi, sqrt #import only selected items


From math import * #import all variables and methods

datetime module

import datetime
tdate= datetime.date.today()
print(tdate)

c=datetime.datetime.now()
print(c.year)
print(c.month)
print(c.day)
print(c.hour)
print(c.minute)
print(c.second)

Packages

Arrange related modules in a tree like hierarchy for easier access. Python package have
directories. Each directory may have subdirectories and files(modules). Each directory must
contain a file named __init__.py to consider it as a package. This file can be an empty file.

game #is a package


__init__.py
sound #is a subpackage or subdirectory
__init__.py
load.py
play.py
image # another subdirectory
__init__.py
open.py #module inside image subdirectory
close.py

Database
Is a file that is organized for storing data. Similar to dictionary but stored in disc so that value
is not lost even after the program ends.

import dbm
db=dbm.open(‘captions’, ’c’) # ‘c’ will create if not existing
db[‘jack.png’] #db is database object
b’photo of john jack #its a byte object
db[‘jack.png’]=”hello” #older content get overwritten

for key in db:


print(key, db[key])
db.close()

Pickling
Write method of file object accept only strings. Pickling is a process of converting an object in
memory to a byte stream that can be stored in a disc. It is also called serialization, flattening or
marshalling. The reverse process is called unpickling.In binary files writing is also called as
dumping and reading is called loading. Picking can be done with all datatypes like int, float,
string, list, tuple, set and dictionary.

import pickle
emp={1:’a’,2:’b’,3:’c’,4:’d’,5:’e’}
pickling_on=open(“emp.pickle”, ’wb’)
pickle.dump(emp, pickling_on)
pickling_on.close()

pickle_off=open(“emp.pickle”,’rb’)
emp=pickle.load(pickle_off)
print(emp)

You might also like