0% found this document useful (0 votes)
71 views43 pages

Unit - 5 PSP

This document covers the concepts of files, modules, and packages in Python, including file operations such as reading, writing, and closing files, as well as handling exceptions and errors. It explains file types, operations, and methods like read(), write(), and the use of the with statement for file handling. Additionally, it discusses the organization of code using modules and packages, along with illustrative programs for practical understanding.

Uploaded by

danukrishnan003
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)
71 views43 pages

Unit - 5 PSP

This document covers the concepts of files, modules, and packages in Python, including file operations such as reading, writing, and closing files, as well as handling exceptions and errors. It explains file types, operations, and methods like read(), write(), and the use of the with statement for file handling. Additionally, it discusses the organization of code using modules and packages, along with illustrative programs for practical understanding.

Uploaded by

danukrishnan003
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/ 43

UNIT – 5

FILES,
MODULES,
PACKAGES
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. It is used to permanently store data in
a non-volatile memory (e.g. hard disk). Since,
random access memory (RAM) is volatile which
loses its data when computer is turned off, we use
files for future use of the data.
 A collection of data or information that has a name,
called the filename.
 Almost all information stored in a computer must be
in a file.
TYPES OF FILES

 Data files
 Text files
 Program files
 Directory files
File Operations
 In Python, a file operation takes place in the following
order.

i. Open the file

ii. Read or write (Data Updating - perform operation)

iii. Close the file


1. Open a file
Syntax

file_object = open(“filename”,
“mode”)

 file_object is the variable to add the file object

 mode – tells the interpreter and developer which


way the file will be used.
FILE OPENING MODE
Open a file
Example :

f = open(“test.txt”) # open file in current


directory
(or)
f = open(“C:/Python3.3/sample.txt”) # specifying
full path
 f = open(“test.txt”) # equivalent to ‘r’ or ‘rt’

 f = open(“test.txt”,“w”) # write in text mode

 f = open(“homepg.bmp”,“r+b”) # read and write in

binary mode
2. Reading and writing files

 In general, there are two methods to manipulate the

files, they are given below:

a) write()

b) read()
write() Method
 This method writes any string to an open file. It is
important to note that Python strings can have
binary data and not just text.
 The write() method does not add a newline
character (‘\n’) to the end of the string.
Syntax

fileObject.write(string)
sam1.txt
Example I will try my best.
God is always with me!!
 # Open a file

 f= open(“sam1.txt”, “wb”)

 f.write( “I will try my best.\nGod is always with


me!!\n”);

 # Close opened file

 f.close()
read() Method
 This method reads a string from an open file. It is
important to note that Python strings can have
binary data apart from text data.
 Count parameter is the number of bytes to be read
from the opened file. This method starts reading
from the beginning of the file and if count is
missing, then it tries to read as much as possible,
maybe until the end of file. Syntax

fileObject.read((count))
sample.txt
Example-1 I will try my best.
God is always with me!!
 # Open a file

 f= open(“sam1.txt”, “r+”)

 str=f.read(10);

 print(str)

 # Close opened file

 f.close()

Output :

I will try
sample.txt
readLine() functionI will try my best.
God is always with me!!
 # Open a file

 f= open(“sam1.txt”, “r+”)

 print(f.readLine())

 # Close opened file

 f.close()

Output :

I will try my best.


3. Close a file
 This method of a file object flushes any unwritten
information and closes the file object, after which no
more writing can be done.

 Python automatically closes a file when the reference


object of a file is reassigned to another file
Syntax

file_object .close()
sample.txt
Example I will try my best.
God is always with me!!
 # Open a file

 f= open(“sam1.txt”, “r+”)

 str=f.read(10);

 print(str)

 # Close opened file

 f.close()

Output :

I will try
Looping over a file object
 The user want to read – or return – all the lines from a
file in a more memory efficient, and fast manner, user
can use the loop over method. The advantage to using
this method is that the related code is both simple and
Welcome to
Example
easy to: read. Akshaya college
By
file = open(“samtext.txt”, 2017 Batch
“r”)
for line in file: Output
print line Welcome to
Akshaya college
By
2017 Batch
With Statement
 The user can also work with file objects using the with
statement. It is designed to provide much cleaner
syntax and exceptions handling when you are working
with code.
Advantages
If any files opened will be closed automatically after
you are done. This leaves less to worry about during
Welcome to
cleanup. Akshaya college
Example : By
2017 Batch
with open(“testfile.txt”) as
file: Output
WELCOME TO
data = file.read() AKSHAYA COLLEGE
print(data.upper()) BY
2017 BATCH
Splitting Lines in a Text File
 This function that allows you to split the lines taken from a
text file. What this is designed to do, is split the string
contained in variable data whenever the interpreter
encounters a space character.
Example : Welcome to Akshaya college
By 2017 Batch
with open(“hello.text”, “r”)
as f:
data = f.readlines() Output
for line in data: [“Welcome”, “to”,
words = line.split() “Akshaya”, “By”, “2017”,
“Batch”]
print words
The file Object Attributes
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.
FILE MANIPULATIONS
 There are two major methods are play the vital role,
they are:
(i) tell()
(ii) seek()
 The tell() method tells you the current position within
the file; in other words, the next read or write will
occur at that many bytes from the beginning of the
file. From Reference
position
 The seek(offset[, from]) method changes the current 0 Beginning of a
file position. The offset argument indicates the file
number of bytes to be moved. The from argument 1 Current
position of a
specifies the reference position from where the bytes file
are to be moved. 2 End of a file
Example : Welcome to Akshaya college
# Open a file By
2017 Batch
fo = open(“sam1.txt”, “r+”)
str = fo.read(10);
print (“Read String is : ”, str)
# Check current position
position = fo.tell();
print (“Current file position : ”, position)
# Reposition pointer at the beginning onceOutput
againposition = fo.seek(0, 0); Read String is : Welcome to
str = fo.read(10); Current file position : 10
print (“Again read String is : ”, str) Again read String is : Welcome to
# Close opend file
fo.close()
Renaming a File
 rename() Method
The rename() method takes two arguments,
the current filename and the new filename.
 Syntax

os.rename(current_file_name, new_file_name)

 Example
import os
# Rename a file from test1.txt to test2.txt
os.rename( “test1.txt”, “test2.txt” )
Deleting a File
 remove() Method
This method is used to delete files by
supplying the name of the file to be deleted as the
argument.
 Syntax

os.remove(file_name)

 Example
import os
# Rename a file from test1.txt to test2.txt
os.remove( “test1.txt”)
Command-line options and
arguments
 Python provides a getopt module that helps you
parse command-line options and arguments.

>>> python test.py arg1 arg2 arg3

 The Python sys module provides access to any


command-line arguments via the sys.argv. This
serves two purposes, they are:
sys.argv is the list of command-line arguments.
len(sys.argv) is the number of command-line
arguments.
Here sys.argv[0] is the program (ie) script name.
ERRORS AND EXCEPTIONS
 Errors or mistakes in a program are often referred to as
bugs. They are almost always the fault of the
programmer. The process of finding and eliminating
errors is called debugging. Errors can be classified into
three major groups:

a) Syntax errors

b) Runtime errors

c) Logical errors
HANDLING EXCEPTIONS
 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.
 Python provides two very important features to handle
any unexpected error in the Python programs and to
add debugging capabilities in them.
i) Exception Handling
ii) Assertions
Standard Exceptions
Assertions
 An assertion is a sanity-check that you can turn on or
turn off when you are done with your testing of the
program.

 The easiest way to think of an assertion is to liken it to


a raise-if statement (or to be more accurate, a raise-if-
not statement). An expression is tested, and if the
result comes up false, an exception is raised.

 Syntax :

assert Expression[, Arguments]


Example :
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),“Colder than absolute zero!”
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)

Output
32.0
451
Traceback (most recent call last):
File “test.py”, line 9, in
print KelvinToFahrenheit(-5)
File “test.py”, line 4, in KelvinToFahrenheit
assert (Temperature >= 0),”Colder than absolute zero!”
AssertionError: Colder than absolute zero!
Logic – HandlingExceptions
Syntax :
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this
block.
except ExceptionII:
If there is ExceptionII, then execute
this block
.......................
else:
If there is no exception then execute
this block.
mportant points about syntax:

A single try statement can have multiple except


statements. This is useful when the try block contains
statements that may throw different types of exceptions.
You can also provide a generic except clause, which
handles any exception.
After the except clause(s), you can include an else-
clause. The code in the else-block executes if the code in
the try: block does not raise an exception.
The else-block is a good place for code that does not
need the try: block’s protection.
Example :
try:

fh = open(“testfile”, “r”)

fh.write(“This is my test file for exception handling!!”)

except IOError:

print “Error: can’t find file or read data”

else:

print “Written content in the file successfully”


Output

Error: can’t find file or read data


Advantages of exception
handling:
 It separates normal code from code that handles errors.

 Exceptions can easily be passed along functions in the


stack until they reach a function which knows how to
handle them. The intermediate functions don’t need to
have any error-handling code.

 Exceptions come with lots of useful error information


built in – for example, they can print a traceback which
helps us to see exactly where the error occurred.
MODULES
 A module allows you to logically organize the 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.
Example :
 import fibo
 This does not enter the names of the functions defined in fibo directly
in the current symbol table; it only enters the module name fibo
there. Using the module name you can access the functions:
 fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
 fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
 fibo.__name__
 ‘fibo’
 If you intend to use a function often you can assign it to a local name:
 fib = fibo.fib
 fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
import statement
 You can use any Python source file as a module by
executing an import statement in some other
Python source file.
 Syntax:

import module1[, module2[,...


moduleN]
The from...import Statement
 Python’s from statement lets you import specific
attributes from a module into the current
namespace.

Syntax:
from modname import name1[, name2[, ...
nameN]]
PACKAGES
 A package is a hierarchical file directory structure that
defines a single Python application environment that
consists of modules and subpackages and sub-
subpackages, and so on.
 Consider a file Pots.py available in Phone directory. This
file has following line of source code:
 def Pots():
 print “I’m Pots Phone”
 Similar way, we have another two files having different
functions with the same name as above:
 Phone/Isdn.py file having function Isdn()
 Phone/G3.py file having function G3()
 Now, create one more file __init__.py in Phone directory:
Phone/__init__.py

To make all of your functions available when you’ve imported Phone, you need
to put explicit import statements in __init__.py as follows:
from Pots import Pots
from Isdn import Isdn
from G3 import G3
After you add these lines to __init__.py, you have all of these classes available
when you import the Phone package.
# Now import your Phone Package.Output
import Phone
I’m Pots Phone
Phone.Pots()
I’m 3G Phone
Phone.Isdn()
I’m ISDN Phone
Phone.G3()
ILLUSTRATIVE PROGRAMS
Program 1: Word Count
# Word Count
file=open(“C:/python27/python operators.txt”,”r+”)
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for k,v in wordcount.items():
print k, v
Program 2: Copy Files
# Copy Files
from shutil import copyfile
while True:
print(“Enter ‘x’ for exit.”)
sourcefile = input(“Enter source file name: “)
destinationfile = input(“Enter destination file name: “)
if sourcefile == ‘x’:
break
else:
copyfile(sourcefile, destinationfile)
print(“File copied successfully!”)

You might also like