Practical8 Python Programming Jeb6qONhW8

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

SVKM’s NMIMS University

Mukesh Patel School of Technology Management & Engineering/ School of Technology


Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

PRACTICAL 8
Part A (To be referred by students)

File and Exception Handling


SAVE THE FILE AND UPLOAD AS (RollNo_Name_Exp8)
Problem Statement:

Understand and apply the various file handling operations to implement following programs

1. Implement a program to handle arithmetic exception


2. Write a program to handle following exceptions
a. Type Error
b. Value Error
c. Make use of else with exception and check its effect
3. Write a program to write 1-20 numbers in a file & display same to the user.
4. Write a program to copy contents (your details) of one file to another file and display
contents of both the files.
5. Write a python script to continue writing to a file until user enters choice as y and
then on user input n stop writing and read the file and count words in the text file
those are ending with alphabet "e".
6. Write a python script to count the number of lines from a text file which is not starting
with an alphabet "T".
7. Write a python script to delete the specified line giving the line number from the text
file.
8. Program to set file offsets with seek( ) and tell( ) functions in python

Topic covered: File Handling and Exception Handling

Learning Objective: Learner would be able to


1. Understand the various file handling operations
2. Apply the various file handling operations
3. Use exception handling
4. Implement file handling programs using exception handling

1|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

Theory:
Data stored in variables and lists is temporary — it’s lost when the program terminates.
Python allows a program to read data from a file or write data to a file. Once the data is saved
in a file on computer disk, it will remain there after the program stops running. The data can
then be retrieved and used at a later time.

There are two types of files in Python - text files and binary files.
 A text file is processed as a sequence of characters. In a text file there is a special
end-of-line symbol that divides file into lines. In addition, you can think that there is a
special end-of-file symbol that follows the last component in a file. A big advantage
of text files is that it may be opened and viewed in a text editor such as Notepad.

 A binary file stores data that has not been translated into character form. Binary files
typically use the same bit patterns to represent data as those used to represent the data
in the computer's main memory. These files are called binary files because the only
thing they have in common is that they store the data as sequences of zeros and ones.

Steps to process file Input/output in Python:


Step 1. Open the file : Opening a file creates a connection between the file and the program.
Step 2. Process the file : In this step data is either written to the file (if it is an output file) or
read from the file (if it is an input file).
Step 3. Close the file : When the program is finished using the file, the file must be closed.
Closing a file disconnects the file from the program.

Python File Handling Operations:


 Open
 Read
 Write
 Close
Other operations include:
 Rename
 Delete

Opening a File
- Open()
- Fileheader =open(‘file name’,”open mode”,”buffering”)
- Various file opening modes
o w
o r
o a

- Example:-
F=open(“myfile.txt”,”w”)

2|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

Closing File:-
f.close( )
Example:- Writing Contents to file:
f=open('myfile.txt','w')
str=input('Enter text to write to file')
f.write(str)
f.close()

Example: - Reading Contents from file:


f=open('myfile.txt','r')
str=f.read( )
print(str)
f.close()

Example:- Reading first few Contents from file:


f=open('myfile.txt','r')
str=f.read(5 )
print(str)
f.close()

Program to store group of strings in file?


f=open('myfile.txt','w')
print('Enter text and enter @ at end ')
while str!='@':
str=input()
if(str!='@'):
f.write(str+'\n')

f.close()

Program to read strings in file


f=open('myfile.txt','r')
print(‘File Contents are… ')
str=f.read()
print(str)
f.close()

Program to know whether file exits or not…


import os,sys
fname=input('Enter file name')
if os.path.isfile(fname):
f=open(fname,'r')
else:
print('file not exist')

3|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

sys.exit()
print('File contents are')
str=f.read()
print(str)
f.close()

The With statement:


- It is used while opening file.
- It take care of closing file
- Need not to close file explicitly
- In case of exception also, it close the file before the exception is handled
- Syntax:-
With open(“filename”, “openmode”) as fileobject:
- Example:-
with open(‘myfile.txt’,’w’) as f:
f.write(“This contents are written”)

Python File Methods:


Python has various method available that we can use with the file object. The following table
shows file method.

Method Description
read() Returns the file content.
readline() Read single line
readlines() Read file into a list
truncate(size) Resizes the file to a specified size.
write() Writes the specified string to the file.
writelines() Writes a list of strings to the file.
close() Closes the opened file.
seek() Set file pointer position in a file
tell() Returns the current file location.
Returns a number that represents the stream, from the operating
fileno()
system's perspective.
flush() Flushes the internal buffer.

4|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

Reading a File:
In order to read a file in python, we must open the file in read mode.
There are three ways in which we can read the files in python.
 read([n])
 readline([n])
 readlines()
Here, n is the number of bytes to be read.
# Reading the entire file at once
filename = “C:/Documents/Python/test.txt”
filehandle = open(filename, ‘r’)
filedata = filehandle.read()
print(filedata)
--OR—
with open("large_file.txt", "r") as f:
print(f.read())

# Using this function we can read the content of the file on a line by line basis
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline())
--OR—
with open("large_file.txt", "r") as f:
print(f.readline())

# reading all the lines present inside the text file including the newline characters and
# display as a list
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readlines())

# Print a specific line from the file, ex: line4


line_number = 4
fo = open(“C:/Documents/Python/test.txt”, ’r’)
currentline = 1
for line in fo:
if(currentline == line_number):
print(line)
break
currentline = currentline +1

Writing into a file:


In order to write data into a file, we must open the file in write mode.

5|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

We need to be very careful while writing data into the file as it overwrites the content present
inside the file that you are writing, and all the previous data will be erased.

Two methods for writing data into a file:


 write(string)
 writelines(list)

my_file = open(“C:/Documents/Python/test.txt”, “w”)


my_file.write(“Hello World\n”)
my_file.write(“Hello Python”)

fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]


my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.writelines(fruits)

Append to File:

To append data into a file we must open the file in ‘a+’ mode so that we will have access to
both the append as well as write modes.

my_file = open(“C:/Documents/Python/test.txt”, “a+”)


my_file.write (“Strawberry”)

fruits = [“\nBanana”, “\nAvocado”, “\nFigs”, “\nMango”]


my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.writelines(fruits)

The tell() and seek() methods:


Python provides seek() and tell() methods to access data in a random fashion in a file.

The tell() method returns the current file position in a file stream. Syntax:

file_object.tell()
The seek() method sets the current file position in a file stream and returns the new position.
Syntax:

file_object.seek(offset [, reference_point])
where offset means how many positions you will move; reference_point defines your point of
reference:
0: means your reference point is the beginning of the file
1: means your reference point is the current file position
2: means your reference point is the end of the file

6|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

infile = open("testfile.txt","r")

print("Initially, the position is: ",infile.tell())


infile.seek(10)

print("Position after moving 10 bytes is:",infile.tell())


infile.seek(0,2)

print("Last position of file: ",infile.tell())

f = open("sample.txt", "r")

# read first line


f.readline()

# get current position of file handle


print(f.tell())

f = open("sample.txt", "r")

# move to 11 character
f.seek(11)

# read from 11th character


print(f.read())

7|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

PRACTICAL 8
Part B (to be completed by students)

File and Exception Handling


1. All the students are required to perform the given tasks in Jupyter Notebook
2. Create a new notebook for each experiment. The filename should be
RollNo_Name_Exp8)
3. In the first cell, the student must write his/her Name, roll no and class in the form of
comments
4. Every program should be written in separate cells and in the given sequence
5. After completing the experiment, download the notebook in pdf format. The filename
should be RollNo_Name_Exp8.pdf).
Note: - To download as a PDF, go to File and choose Print Preview. This will open a
new tab. Now, press Ctrl + P and opt to save as PDF.
OR
Download notebook as HTML and open downloaded html(webpage), press CTRL+P
and opt to save as PDF.
6. Upload the pdf on the web portal

8|Page

You might also like