0% found this document useful (0 votes)
15 views8 pages

Python File Handling and Exceptions

2

Uploaded by

sagargurav1812
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views8 pages

Python File Handling and Exceptions

2

Uploaded by

sagargurav1812
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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(“[Link]”,”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:-
[Link]( )
Example:- Writing Contents to file:
f=open('[Link]','w')
str=input('Enter text to write to file')
[Link](str)
[Link]()

Example: - Reading Contents from file:


f=open('[Link]','r')
str=[Link]( )
print(str)
[Link]()

Example:- Reading first few Contents from file:


f=open('[Link]','r')
str=[Link](5 )
print(str)
[Link]()

Program to store group of strings in file?


f=open('[Link]','w')
print('Enter text and enter @ at end ')
while str!='@':
str=input()
if(str!='@'):
[Link](str+'\n')

[Link]()

Program to read strings in file


f=open('[Link]','r')
print(‘File Contents are… ')
str=[Link]()
print(str)
[Link]()

Program to know whether file exits or not…


import os,sys
fname=input('Enter file name')
if [Link](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

[Link]()
print('File contents are')
str=[Link]()
print(str)
[Link]()

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(‘[Link]’,’w’) as f:
[Link](“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/[Link]”
filehandle = open(filename, ‘r’)
filedata = [Link]()
print(filedata)
--OR—
with open("large_file.txt", "r") as f:
print([Link]())

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

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

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


line_number = 4
fo = open(“C:/Documents/Python/[Link]”, ’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/[Link]”, “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/[Link]”, “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/[Link]”, “a+”)


my_file.write (“Strawberry”)

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


my_file = open(“C:/Documents/Python/[Link]”, “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("[Link]","r")

print("Initially, the position is: ",[Link]())


[Link](10)

print("Position after moving 10 bytes is:",[Link]())


[Link](0,2)

print("Last position of file: ",[Link]())

f = open("[Link]", "r")

# read first line


[Link]()

# get current position of file handle


print([Link]())

f = open("[Link]", "r")

# move to 11 character
[Link](11)

# read from 11th character


print([Link]())

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

Common questions

Powered by AI

The 'readline()' method reads a single line from a file, making it suitable for processing files line-by-line, especially when dealing with large files where it is memory-efficient. In contrast, 'readlines()' reads all lines of a file into a list at once, which is useful for smaller files or when needing to preserve the structure of data as a list for further operations .

File modes in Python determine how a file is opened and what kind of operations are permitted. For instance, 'r' mode opens a file for reading, preserving existing content; 'w' mode opens a file for writing, which overwrites existing content or creates a new file; and 'a' mode appends data to the end of the file, preserving existing content. Using 'r+' allows both reading and writing without truncating the file, while 'a+' allows reading and appending .

The 'with' statement in Python simplifies file handling by ensuring that the file is properly opened and closed, even if an error occurs during the file operations. This reduces the risk of leaving files open, which can lead to file corruption or memory leaks. Unlike traditional file operations that require explicit closing of the file using the 'close()' method, the 'with' statement manages this automatically, making the code cleaner and more reliable .

The seek() function in Python is used to change the file pointer's position within a file. This function takes an offset and a reference point: 0 for the start, 1 for the current position, and 2 for the end of the file. By adjusting the file pointer, seek() allows programmers to read data from any point in the file, enabling flexible data processing such as skipping irrelevant parts or re-reading certain sections .

The 'truncate()' method in Python resizes a file to a specified size. When used, it can shorten or extend the file. In practice, it's often used to clear or reset files to a specified state for logging purposes or to remove old data beyond a certain point. For example, in a log rotation system, 'truncate()' can trim older entries to keep logs within a manageable size .

Properly handling exceptions is crucial in file operations to prevent unintended crashes and ensure the program can handle unforeseen errors, such as file not found or permission denied issues. Exception handling provides a mechanism to deal with these errors gracefully, allowing the program to continue running or provide meaningful error messages. This improves the robustness and user-friendliness of applications .

Text files are preferable when the data needs to be human-readable or easily editable by various text editors, which is useful in configuration files or simple data logging. Binary files are advantageous for compact data storage, performance efficiency, and handling complex data types like images or executables. The decision depends on the need for data readability versus storage efficiency .

Python uses the 'flush()' method to clear the internal buffer, sending any unwritten data to the file. This is crucial because operating systems typically manage IO operations in large chunks to optimize performance, meaning changes might remain in memory instead of being immediately written to physical storage. Ensuring data integrity especially in critical applications requires the buffer to be flushed regularly, like after every critical write operation .

The 'try-except-else' structure allows for handling exceptions specifically and definitively. The 'else' block runs if no exceptions are raised in the 'try' block, thereby separating normal execution code from error handling code. This is useful in file operations where code outside 'try-except' might involve dependent tasks, like processing data only if file reading is successful, preventing accidental processing of erroneous or incomplete data .

Variables in programming languages like Python reside in volatile memory (RAM), which loses its data when the program terminates or the computer reboots. In contrast, files are stored on non-volatile storage mediums such as hard drives, preserving data across sessions and reboots, thus providing a more permanent storage solution .

You might also like