0% found this document useful (0 votes)
2 views13 pages

Module IV Python

This document provides a comprehensive overview of file operations in Python, detailing methods for reading, writing, and managing files effectively. It covers essential functions like open(), read(), write(), and seek(), along with file modes and the differences between text and binary files. Additionally, it introduces exception handling concepts, including how to manage errors using try-except blocks and create custom exceptions.

Uploaded by

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

Module IV Python

This document provides a comprehensive overview of file operations in Python, detailing methods for reading, writing, and managing files effectively. It covers essential functions like open(), read(), write(), and seek(), along with file modes and the differences between text and binary files. Additionally, it introduces exception handling concepts, including how to manage errors using try-except blocks and create custom exceptions.

Uploaded by

Ab Cd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Working with File Operations in Python

In this chapter, we’ll explore how to work with files in Python, including
reading, writing, and managing files efficiently. Files are often used to store
inputs or outputs during script execution, and Python’s built-in support for
file handling makes this process easy. We’ll go over the most commonly
used file handling methods like open(), read(), write(), and seek().
You’ll also learn about file modes, binary files, and how Python manages
buffering when handling large amounts of data. By the end of this chapter,
you’ll be equipped to handle text and binary files in Python with confidence.

Commonly Used File Handling Functions :


File Function Description

open() Used to create or open a file.

fid.read() Reads the entire content or specific


bytes.

fid.readline() Reads a file line by line.

fid.write() Writes data to a file.

fid.writelines() Writes multiple lines to a file.

fid.seek() Moves the file object to a specific


position.

fid.tell() Returns the current position of the


file object.

fid.readable() Checks if the file is readable.

fid.writable() Checks if the file is writable.


Opening a File Using open()

The open() function is used to open a file and returns a file object. This
file object can be used to read, write, or manipulate the file using methods
like read(), write(), and close().

Syntax:
fid = open("abcd.txt", "r")

The first argument is the file name. The second argument ("r") is the
mode, indicating how the file should be opened.

File Modes:
Mode Description

r Opens the file for reading. The file


must exist.

r+ Opens the file for both reading and


writing. The file must exist.

w Opens the file for writing. If the file


doesn’t exist, it will be created.

w+ Opens the file for reading and


writing. If the file doesn’t exist, it is
created.

a Opens the file for appending. If the


file doesn’t exist, it is created.

a+ Opens the file for both appending


and reading

x Creates a new file for writing.


Raises an exception if the file
exists.
Reading from a File

We can read the contents of a file in a couple of ways. Make sure the file is
present before using the ‘read’ mode. If the file is not present, an ‘OSError’
will be raised.Before trying the following code, create a file named ‘abcd.txt’
with the following lines in the same folder where you are executing your
script.

File name : abcd. txt


ethernet0 status: up
ethernet1 status: down
ethernet2 status: up

Method 1. Using read() : The read() function reads the entire content of
a file as a string.
fid = open("abcd.txt", "r")
tmp = fid.read()
print(tmp)

#Output:
ethernet0 status: up
ethernet1 status: down
ethernet2 status: up

Explanation:
The read() function reads the entire file and returns it as a string. You can
also specify a number of bytes to read.

Method 2: Using readline()


fid = open("abcd.txt", "r")
print(fid.readline())

#Output :
ethernet0 status: up

Explanation: The readline() function reads one line at a time from the file.
This is useful when you want to process files line by line.
Method 3: Using readlines()
fid = open("abcd.txt", "r")
print(fid.readlines())

#Output :
['ethernet0 status: up\n', 'ethernet1 status: down\n',
'ethernet2 status: up\n']

Explanation:
The readlines() function reads the entire file and returns it as a list
where each element is a line from the file.

Writing to a File Using write()

The write() function is used to write data to a file. If the file is opened in
"w" mode, any existing content will be deleted before writing new content.
fid = open("abcd.txt", "w")
fid.write("hello world")
fid.close()

Explanation:
This code opens the file abcd.txt in write mode ("w"), writes the string
"hello world", and then closes the file. Writing in "w" mode overwrites
the existing content.

Appending to a File Using writelines()

The writelines() function writes a list of lines to a file without adding


newlines unless specified in the data.
a = ['ethernet0 status: up\n', 'ethernet1 status:
down\n', 'ethernet2 status: up\n']
fid = open("xyz.txt", "w")
fid.writelines(a)
fid.close()
Explanation:
This code writes multiple lines to the file xyz.txt using the
writelines() method.

Moving the Cursor with seek() and Getting the


Position with tell()

Using seek(): The seek() function moves the cursor to a specified


position in the file. The first argument is the number of bytes, and the
second argument is the reference position (0 for the start, 1 for the current
position, and 2 for the end).
fid.seek(5, 0) # Moves cursor to 6 bytes from the
start
fid.seek(-5, 2) # Moves cursor 5 bytes before the end

Using tell(): The tell() function returns the current position of the
cursor.
position = fid.tell()
print(position)

Explanation:
This method is useful for tracking where the cursor is located in the file
during reading or writing operations.

Differences Between r+ and w+ Modes

r+ allows both reading and writing without overwriting the content. If you
read the file first, the cursor moves to the end, and any writing will append
at the end.

w+ allows reading and writing, but it first clears the file content, so there’s
nothing to read unless you write something first.

Text Files vs Binary Files


Text Files: Store data in the form of text strings with specific encoding like
UTF-8 or ASCII. End of line (EOL) characters vary by platform (\r\n for
Windows, \n for Linux).

Binary Files: Store data like images, audio, or executables. No encoding or


EOL conversion is performed by Python for binary files. For binary
operations, use modes like "rb", "wb", "ab".

Buffering in File Operations

When reading or writing to a file, Python stores data in a buffer to improve


performance. The buffer is a temporary storage that holds chunks of data,
making operations faster.
import io
print(io.DEFAULT_BUFFER_SIZE)

#Output :
8192

Explanation:
The default buffer size is 8192 bytes. You can control buffering with the
buffering parameter in open(). Set buffering=0 to disable buffering,
buffering=1 for line buffering, or provide a specific buffer size in bytes.

Some Additional File Attributes:

● fid.encoding: Returns the file encoding (e.g., ‘UTF-8’).


● fid.mode: Shows the mode in which the file is opened (e.g., ‘r’).
● fid.readable(): Checks if the file is readable.
● fid.writable(): Checks if the file is writable.
● fid.seekable(): Checks if the file supports seeking.
● fid.name: Returns the file name.
Programming Exercises:

1.Write a Python program to count the number of words in a file.


2.Write a Python program to count the number of lines in a file.
3.Write a Python program to copy the contents of one file to another.
4.Write a Python program to print lines 2 to 5 from a file (assuming the
file has more than 5 lines).
5. Write a Python program to insert a new line at the beginning of a file.
6. Write a Python program to replace a specific line in a file with another
line.
7. Write a Python program to move the contents of a file into an array
(list).
8. Write a Python program to print the last two lines of a file.
Router# show ip interface brief

Interface IP-Address Status Protocol

Ethernet0 10.1.1.1 up up

Ethernet1 unassigned down down

Loopback0 20.1.1.1 up up

Serial0 30.1.1.1 up up

9. Store the above lines in a file and:


1. Write a Python program to check if a given IP address is
present in the file.
2. Write a Python program to find the status of a given interface.
3. Write a Python program to count how many interfaces are “UP.”
4. Write a Python program to print the names of all interfaces that
are “UP.”
Understanding Exception Handling in
Python
What is an Exception?

Exceptions are errors that occur during the execution of your code. Before
running a script, Python checks for syntax errors, but even if the syntax is
correct, runtime errors, called exceptions, can still occur. In this chapter,
we’ll explore how exceptions work in Python and how you can handle them
using try, except, else, and finally blocks. We’ll also cover handling
multiple exceptions, raising your own exceptions, and using the assert
statement for validation. By the end of this chapter, you’ll know how to
handle errors gracefully in your programs and ensure they run smoothly
even when something goes wrong.

For example, in the code below, there are no syntax errors. However, during
execution, the 2nd line “c = a / b” will cause an exception because the
value of the variable “b” is zero and dividing by zero is not allowed.
a, b = 10, 0
c = a / b

#Output:
Traceback (most recent call last):
File "except.py", line 2, in <module>
c = a / b
ZeroDivisionError: division by zero

Some other common exceptions are: ValueError, TypeError, NameError,


SyntaxError, FileNotFound Error etc

ValueError : This exception is raised when a function gets a valid data type
but an invalid value. For example, trying to convert a non-numeric string
into an integer as show in below code:
a = "hi"
b = int(a)
#Output:
Traceback (most recent call last):
File "except.py", line 2, in <module>
b = int(a)
ValueError: invalid literal for int() with base 10:
'hi'

TypeError: Raised when you perform an operation on a data type that


doesn’t support it. For example, trying to add a string and an integer
together as shown below:
a = "hello" + 5

#Output :
Traceback (most recent call last):
File "except.py", line 1, in <module>
a = "hello" + 5
TypeError: can only concatenate str (not "int") to str

NameError: Raised when a variable or function name is not found in the


local or global namespace. For example, the following simple code uses a
variable that hasn’t been defined and will raise a NameError.
a = hello

#Output:
Traceback (most recent call last):
File "except.py", line 1, in <module>
a = hello
NameError: name 'hello' is not defined

FileNotFoundError: Raised when attempting to open a file that does not


exist. For example, the following code uses the open function to open the
file abcd.txt in read-only mode and will raise a FileNotFoundError if the
file does not exist in the same folder as the script.
file_id = open ("abcd.txt" , r)

#Output:
Traceback (most recent call last):
File "except.py", line 1, in <module>
fid = open("abcd.txt", 'r')
FileNotFoundError: [Errno 2] No such file or directory:
'abcd.txt'

What is Exception Handling?

Exception handling is the technique of catching errors to prevent the


unexpected termination of a script. If you suspect a part of your code may
raise an error, you can use the try-except block to handle that exception.

For example, to handle the FileNotFoundError in the code above:


try:
fid = open("abcd.txt", 'r')
except FileNotFoundError:
print("File is not present, skipping the reading
process...")
else:
print(fid.read())
fid.close()

In this code:

● The try block contains the code that might raise an exception.
● If a FileNotFoundError occurs, the except block will be
executed.
● If no error occurs, the else block is executed.

Handling Multiple Exceptions

You can catch multiple exceptions by using either a tuple of exceptions or


multiple except clauses.

Using a Tuple of Exceptions:


try:
fid = open("abcd.txt", 'r')
fid.write("hello world")
except (FileNotFoundError, IOError):
print("Error in opening file or writing ...")
else:
fid.close()

Using Multiple except Clauses:


try:
fid = open("abcd.txt", 'r')
fid.write("hello world")
except FileNotFoundError:
print("Error in opening file")
except IOError:
print("File opened successfully, but couldn't
write")
else:
fid.close()

Using “finally” in Exception Handling :

The “finally" block is used to execute code regardless of whether an


exception is raised. It is typically used to release resources like closing files
or network connections. In the following example, the “finally“ block will
always run, whether or not an exception is raised.
fid = open("abcd.txt", 'r')

try:
fid.write("hello world")
except IOError:
print("Write operation: Failed")
else:
print("Write operation: Successful")
finally:
print("Inside finally...")
fid.close()

User-Defined Exceptions

You can create custom exceptions by defining a new class that inherits
from the built-in “Exception” class. You can use this custom exception
with the “raise” keyword to trigger the exception manually. For example,
the following code will print a range of numbers if the user input is a
number greater than 0 , but will exit the code raising the MyInputError
defined by the user if the user’s input is less than 0.

Raising a Custom Exception:


class MyInputError(Exception):
pass

a = int(input("Enter a number: "))

try:
if a <= 0:
raise MyInputError()
except MyInputError:
print("Enter a number greater than 0")
else:
for tmp in range(a):
print(tmp)

Exception Arguments

When raising an exception, you can pass arguments to it, which can be
used later in the except block or displayed if not caught.
a = int(input("Enter a number: "))

class MyInputError(Exception):
pass

try:
if a < 0:
raise MyInputError("Input is less than 0")
if a < 5:
raise MyInputError("Input is less than 5")
except MyInputError as tmp:
print(tmp)
else:
for tmp in range(a):
print(tmp)

#Output :
Enter a number: 3
Input is less than 5

Python’s “assert” Statement

The “assert" statement is used to verify that a condition holds true. If the
condition is false, an AssertionError is raised.
a = int(input("Enter a number: "))
assert a > 0, "Wrong Input"

for tmp in range(a):


print(tmp)

#Output (If the input is less than or equal to zero)


Traceback (most recent call last):
File "except.py", line 2, in <module>
assert a > 0, "Wrong Input"
AssertionError: Wrong Input

You might also like