Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit V Pyhton Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

UNIT V

File Handling in Python

File:
A file is a collection interrelated Records.
Records:
A record is a collection of interrelated information
Information:
Information is a collection of interrelated data’s
Data:
A data is a collection of facts or raw material.
Python File:
A file can be sequence of bits, bytes, lines of records depending of the application (or)
software used to create it,
For ex.. A test file is organized as a sequence of lines.
Files Types:
The type of a file can be decided using its extension (or) application is used to create a
file.
For ex: Text – Notepad / Word pad
Audio - Media Player
Video - Media player
DOC - M S Word
HTML - Browsers.
EXE - Run Program
.c - C Program
.c++ - C++
.py - Python program
File Handling Methods in Python.

S,No Name of the function Description


1 open( ) To open a file
2 close( ) Close a file
3 read( ) Reads at most n characters from the file
4 read line( ) Read and return one line.
5 tell( ) Returns the current file location.
6 seek( ) Change the file position to offset bytes.
7 write( ) Write strings to the file
8 write line( ) Write a list of lines to the file
9 next( ) Returns to the next line.

File operation:
(i) Opening a file
(ii) Creating a file
(iii) Reading a file
(iv) Writing a file
(v) Appending a file
(vi) Closing a file
Opening a file:
The file must be opened for any file processing like read / write / append.
Syntax: Variable name = open (“file name.Ext”, “mode”)
In the above syntax.
- Variable name is user defined
- Open( ) is a method to open a file
- File name .Ext is user defined
- Modes are
o r - read only
o w - write only
o a - append only
o wt - read / write
o rt - read / write
o at - append / reading
Ex:
fread = open (“student.txt”, “r”)
Creating a file:
To create a file in python, the file should open in write mode with file name are
extension
Syntax:
fcreate =open (“student.txt”, “w”)
Reading file:
In python the text file can be read in four different ways, they are
(i) using read method
(ii) using read lines method
(iii) using foe line to file method
(iv) using read line method
The General syntax to read a file in python.
Variable name = read(size)
In the above syntax.
- Variable name is user defined
- read( ) is a method
- Size is optional
(i) # ex.program for file read upto 20characters
fileread = open (“student.txt”,”r”)
str= fileread.read(20)
length=len(str)
print str
print length
(ii) #ex.program to read all characters in file
fread=open(“student.txt”, “r”)
Str=fread.read()
Length=len(str)
print str
print length
fread.close()
(iii) #ex.program to read lines of a file
fread=open(“student.txt”, “r”)
str=fread.readlines()
Length=len(str)
print str
fread.close()
(iv) #ex.program to read a single line of a file
fread=open(“student.txt”, “r”)
str=fread.readline()
Length=len(str)
print str
fread.close()
(v) #ex.program to read the content of file using for loop
fread=open(“student.txt”, “r”)
for 1 in fread
print l
fread.close()
Writing a file:
A file can be created a non existing file in write made in python (or) we can write a
existing file in append mode.
Syntax:
variablename = open(“filename.ext”,”w”)
In the above syntax
- Variable name is user defined
- Open() is a method
- Filename is user defined
- “w” is write mode
Ex: (i) #Writing a file
Filewrite=open(‘student.txt”,”w”)
Filewrite.writelines([“welcome to python”])
Filewrite.close()
Ex: (ii) #Writing the contents of a file
Filewrite=open(‘student.txt”,”w”)
Filewrite.write([“welcome to python”])
Filewrite.close()
Appending a file:
Adding (or) writing a new content to an existing file is called appending a file
in python
Syntax:
Varname=open(“filename.ext”, ”mode”)
Ex: fappend=open(“student.txt”, “a”)
Ex (i) #program for appending
Fileappend=open(“student.txt”, “a”)
Fileappend.writelines([“It is simple and easy”])
Fileappend.close()
Closing a file:
A file must be closed after the file processing is over.
Syntax:
fileobject.close()
Ex: #program for closing
fclose=open(‘student.txt”,”w”)
fclose.fwritelines([“Hello”])
fileclose.close()
Command line arguments:
The command line arguments are arguments send to the program being
executed. sys.argv is a variable that contains the command line arguments passed to
the script.
Ex: #program for command line argument
import sys
NS=len(sys.argv)
IS=Str(sys.srgv)
Print NS
Print IS
Attributes of the object
S.No Attributes Name Description
1 File.closed If the file is closed returns T else False
2 File.mode Returns the file mode
3 File.name Returns the name of the file
4 File.softspace Returns false if space expli required with print true
otherwise
Ex: #program for attributes
file=open(“student.txt”, “w”)
print file.closed
print file.name
print file.mode
print file.softspace
Exception Handling In Python:
Exception handling is also called Error Handling, Errors are caused by the Mistakes
(or) fault in the program.
Types of Errors:
1. Syntax Errors (or) compile time errors:
The syntax errors are rectified by the programmer when the compiler throws
errors. Ex: Indentation errors, : missing ect.
2. Logical Errors:
Logical errors are erroneous output, the program gets executed but the output
is not the desired one. Ex: zero divide by errors.
3. Runtime errors:
Errors are detected during execution / runtime are called exceptions
For ex: x=10/0 carve the program to half abruptly, to rectify these types of
errors in python. We can use exception Handling.
Types of Exception:
There are two types of exceptions
1. Built-in exceptions 2. User defined exceptions
Built-in Exception:
These exception are also called pre defined Exception. The following are built in
exception in python.
S.no Exception Description
1 Exception Base class for all exceptions.
2 Overflow error Raised when a calculation exceeds maximum
limit for a numeric types.
3 Floating point error Raised when a floating point calculations fails
4 Zero division error Raised when division by zero takes place
5 EOF Error Input function & the end of file reached
6 I/O Errors Raised for operating system related errors.
7 Runtime error Raised when a generated errors does not fall
into any category.
8 System exit Raised by the sys.exit in function
9 Lookup error Base class for all lookup errors
10 syntax error Raised when there is an arror in python syntax
Ex: #ex.program for built in exception try:
X=10/0
print “exception in python”
Except:
print ”this is an error message”
User Defined Exception:
Python allows user to define new exceptions. How ever these exceptions are
derived from the standard exception only.
For ex: #program for user \defined exception
class cloud Exception (Exception):
def_int_(self,arg):
self.args=arg
try:
raise cloud exception (“cloud error”)
except cloud exception, e:
print e
Exception Handling (or) Handling Exception:
There are three statements used to handle the exception (or) runtime errors:
1. try:
2. except:
3. raise:
1. try: This statement is used to encounter (or) identity the runtime errors
2. except: This statement is used to handle the exception.
3. raise: This statement is used to force fully invoke an exception
Ex: #program for exception handling
try:
print “Hello”
X=10/0
raise value error (“errors needs to be handled”)
except:
print “zero divide by errors”
Pickling In Python:
Python consists of standard Module. Pickle that preserves the data structures in the
file. The files are opened as usual, however when writing and reading the follow syntax is
used.
Syntax:
import pickle
write pickle:dump(“variable”, “filename”)
read pickle:load(“filename”)
Modules in python
A module is simple python coed that can consist of functions / classes and variables
(or) A module is a file that contains proper python code with .py extension.

Module

class function properties

function properties

Creating Modules:
A module is a python file that has only definitions of variables, function & classes.
Create a module with the suffix .py & then import it using the import command.
Ex: #program for module
def add(x,y):
t=x+y
return t
def mul(x,y):
r=x*y
return r
Save the above program as calc.py
Importing modules:
Python modules are essentially reusable libraries of code that can be imported and
used in a program. The import statement reads a module file & creates a module object.
Syntax:
import modulename
Ex: import math
Types of import statement:
1. Import statement
2. From …..import statement
3. The from….import * statement
1. Import statement: Any function is a python program can be reused in another
python program by using import statement.
Syntax:
importmodule1, module2… module
2. From…import statement: The specific function / classes / variables can be
imported using this statement.
Syntax:
from<module name> import <name1>… <name N>
3. The form…. Import * statement : There are situations where all the function of the
module can be used in the current program then we can use this statement.
Syntax:
from modulename import*
Types of modules:
1. Built in modules
2. User defined modules
1. Built-in module:
These modules are predefined are library modules already in python languages.

Module name function


Math sqrt()
pow()
sin()
cos()
Random choice()
random()
seed()
shuffle()
Date and time time()
data()
Calendar calendar()
month()
firstweekday()
User defined modules:
These modules are created by the user, A module is a python file that has only
definitions of variables / functions and classes.
To create a module with the module name .py & them import it using import
statement. Ex: def add(x,y):
t=x+y
return t
def mul(x,y):
r=x*y
return r
Save as: calc.py where calc is a user defined module
Locating modules:
There are three ways to locate (save) the modules
1. The current directory
2. PYTHONPATH
3. The installation – dependent default directory
Ex: To get path
>>>import sys
>>>sys.path
Ex: To set path
set PYTHONPATH=C:\PYTHON 2.7\lib;
Packages in python:
A package is a hierarchical file directory structure that defines a single python
application environment that consist of modules and sub-packages. A packages is a
directory which contains a special file called –init-.py

a.py b.py -init-.py

Importing modules form a package:


The modules can be imported from packages using the dot(.) operator.
Syntax:
import<packagename>. {sys.package…}
Ex: import mypackage.subpackage.prog\.
Steps to create a python package:
1. Create a directory and insert packages’ name
2. Insert necessary classes into it
3. Create a -init-.py file in that directory
Packages are namespaces which contain multiple packages and modules
themselves. They are simply directories.
Programs in Unit V
1. Write a python program to file copy.
#file copy
file1=input(“Enter the source file name”)
file2=input(“Enter the destination filename”)
fr=open(file1,”r”)
fw=open(file2, “w”)
for line in fr. readlines()
fw.write (line)
fr.close()
fw.close()
print”file copies”
2. Write a python program to count numbers of words in a file
#word count in a file
file=open(“c:\mydocuments\input.
wc={}
for w in file. read().split():
if w not in w():
wc[w]=1
else:
wc[w]=wc[w]+1
print wc
file.close()

UNIT V
Part A Questions
1. Define: File, Record, Information, data
2. List the types of files in python?
3. List the different file modes in python?
4. What are the attributes of file object?
5. Define command line argument.
6. What is exception?
7. What is error? What are the two types of errors
8. How to handle exception in python?
9. What is package?
10. Define module.
11. What is pickling in python?
12. What are the file operation.
Part – B Questions
1. Explain about file handling functions in python.
2. Discuss about modules in python
3. What is an Exception? Explain
4. What is Package? Explain.
5. Write a python program to copy file.
6. Write a python program to count words in a file
7. Explain in detail about file read / file write operation with example.

You might also like