`
UNIT V : FILES, MODULES AND PACKAGES
Files and exceptions: text files, reading and writing files, format operator;
command line arguments, errors and exceptions, handling exceptions, modules,
packages; Illustrative programs: word count, copy file, Voter’s age validation,
Marks range validation (0-100).
5.1 FILES AND EXCEPTIONS
5.1.1 FILES
❖ File is a named location on disk to store related information. It is used to store data
permanently in a memory (e.g. hard disk).
❖ File Types: 1) Text file 2) binary file
Text File Binary file
Text file is a sequence of characters that A binary files store the data in the binary
can be sequentially processed by a format (i.e. 0 s and 1 s ). It contains any
Computer in forward direction. type of data ( PDF, images , Word doc,
Spreadsheet, Zip files,etc)
Each line is terminated with a special No termination character for binary file
character, called the EOL [End Of
Line character]
Operations on Files
In Python, a file operation takes place in the following order,
1. Open a file
2. Write a file
3. Read a file
4. Close a file
Open a file
Syntax: Example:
file_object=open(“ file_name.txt” , mode ) f=open( “sample.txt” , ‘w ‘)
1. Write a file
Syntax: Example:
file_object.write(string) f.write( ‘hello’ )
2. Read a file
Syntax
file_object.read(string) f.read( )
3. Close a file
Syntax
file_object.close() f.close()
Modes description
r read only mode
w write only
a appending mode
1
,`
r+ read and write mode
w+ write and read mode
Differentiate write and append mode
write mode append mode
It is used to write a string into a file. It is used to append (add) a string into a file.
If file does not exist it creates a new file. If file does not exist it creates a new file.
If file is exist in the specified name, the It will add the string at the end of the old file.
existing content will be overwritten by the
given string.
File operations and methods:
S.No Syntax Example Description
1 fileobject.write(string) f.write("hello") Writing a string into a file.
f.writelines (“1st line \n Writes a sequence of strings to
2 fileobject.writelines(sequence) second line” ) the file.
f.read( ) #read entire file To read the content of a file.
3 fileobject.read(size) f.read(4) #read the
first 4 char
4 fileobject.readline( ) f.readline( ) Reads one line at a time.
5 fileobject.readlines( ) f.readlines( ) Reads the entire file and returns
a list of lines.
f.seek(offset,[whence]) Move the file pointer to the
f.seek(0) appropriate position. seek(0)
[whence value is optional.] sets the file pointer to the
starting of the file.
[whence =0 - from beginning] f.seek(3,0) Move three characters from the
6 beginning.
[whence =1 - from current Move three characters ahead
position] f.seek(3,1) from the current position.
[whence =2 - from last f.seek(-1,2) Move to the first character from
position] end of the file
7 fileobject.tell( ) f.tell( ) Get the current file pointer
position.
8 fileobject.flush( ) f.flush( ) To flush the data before closing
any file.
9 fileobject.close( ) f.close( ) Close an open file.
10 fileobject.name f.name Return the name of the file.
11 fileobject.mode f.mode Return the Mode of file.
12 os.rename(old import os Renames the file or directory.
name,new name ) os.rename( 1.txt , 2.txt )
13 os.remove(file name) import os Remove the file.
os.remove("1.txt")
2
, `
Example Programs:
Program 1: Opening and Closing a file "MyFile.txt
file1 = open("MyFile.txt","a")
file1.close()
Program 2: To create a text file by name sample and text is written to it
file = open('sample.txt','w')
file.write("hello")
file.close()
# text file sample is read and content displayed
file = open('sample.txt','r')
print(file.read()) # read the file sample and diplay the output
file.close()
output:
hello
Program 3: # Program to show various ways to read and write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes
file1 = open("myfile.txt","r")
print("Output of Read function is ")
print(file1.read())
# seek(n) takes the file handle to the nth byte from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
Program 4: To display the modes of file
f=open("1.txt","r")
print(f.name)
print(f.closed)
print(f.mode)
f.close()
print(f.closed)
3
UNIT V : FILES, MODULES AND PACKAGES
Files and exceptions: text files, reading and writing files, format operator;
command line arguments, errors and exceptions, handling exceptions, modules,
packages; Illustrative programs: word count, copy file, Voter’s age validation,
Marks range validation (0-100).
5.1 FILES AND EXCEPTIONS
5.1.1 FILES
❖ File is a named location on disk to store related information. It is used to store data
permanently in a memory (e.g. hard disk).
❖ File Types: 1) Text file 2) binary file
Text File Binary file
Text file is a sequence of characters that A binary files store the data in the binary
can be sequentially processed by a format (i.e. 0 s and 1 s ). It contains any
Computer in forward direction. type of data ( PDF, images , Word doc,
Spreadsheet, Zip files,etc)
Each line is terminated with a special No termination character for binary file
character, called the EOL [End Of
Line character]
Operations on Files
In Python, a file operation takes place in the following order,
1. Open a file
2. Write a file
3. Read a file
4. Close a file
Open a file
Syntax: Example:
file_object=open(“ file_name.txt” , mode ) f=open( “sample.txt” , ‘w ‘)
1. Write a file
Syntax: Example:
file_object.write(string) f.write( ‘hello’ )
2. Read a file
Syntax
file_object.read(string) f.read( )
3. Close a file
Syntax
file_object.close() f.close()
Modes description
r read only mode
w write only
a appending mode
1
,`
r+ read and write mode
w+ write and read mode
Differentiate write and append mode
write mode append mode
It is used to write a string into a file. It is used to append (add) a string into a file.
If file does not exist it creates a new file. If file does not exist it creates a new file.
If file is exist in the specified name, the It will add the string at the end of the old file.
existing content will be overwritten by the
given string.
File operations and methods:
S.No Syntax Example Description
1 fileobject.write(string) f.write("hello") Writing a string into a file.
f.writelines (“1st line \n Writes a sequence of strings to
2 fileobject.writelines(sequence) second line” ) the file.
f.read( ) #read entire file To read the content of a file.
3 fileobject.read(size) f.read(4) #read the
first 4 char
4 fileobject.readline( ) f.readline( ) Reads one line at a time.
5 fileobject.readlines( ) f.readlines( ) Reads the entire file and returns
a list of lines.
f.seek(offset,[whence]) Move the file pointer to the
f.seek(0) appropriate position. seek(0)
[whence value is optional.] sets the file pointer to the
starting of the file.
[whence =0 - from beginning] f.seek(3,0) Move three characters from the
6 beginning.
[whence =1 - from current Move three characters ahead
position] f.seek(3,1) from the current position.
[whence =2 - from last f.seek(-1,2) Move to the first character from
position] end of the file
7 fileobject.tell( ) f.tell( ) Get the current file pointer
position.
8 fileobject.flush( ) f.flush( ) To flush the data before closing
any file.
9 fileobject.close( ) f.close( ) Close an open file.
10 fileobject.name f.name Return the name of the file.
11 fileobject.mode f.mode Return the Mode of file.
12 os.rename(old import os Renames the file or directory.
name,new name ) os.rename( 1.txt , 2.txt )
13 os.remove(file name) import os Remove the file.
os.remove("1.txt")
2
, `
Example Programs:
Program 1: Opening and Closing a file "MyFile.txt
file1 = open("MyFile.txt","a")
file1.close()
Program 2: To create a text file by name sample and text is written to it
file = open('sample.txt','w')
file.write("hello")
file.close()
# text file sample is read and content displayed
file = open('sample.txt','r')
print(file.read()) # read the file sample and diplay the output
file.close()
output:
hello
Program 3: # Program to show various ways to read and write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes
file1 = open("myfile.txt","r")
print("Output of Read function is ")
print(file1.read())
# seek(n) takes the file handle to the nth byte from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
Program 4: To display the modes of file
f=open("1.txt","r")
print(f.name)
print(f.closed)
print(f.mode)
f.close()
print(f.closed)
3