Module IV Python
Module IV 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.
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
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.
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.
#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.
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.
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.
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.
#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.
Ethernet0 10.1.1.1 up up
Loopback0 20.1.1.1 up up
Serial0 30.1.1.1 up up
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
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'
#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
#Output:
Traceback (most recent call last):
File "except.py", line 1, in <module>
a = hello
NameError: name 'hello' is not defined
#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'
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.
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.
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
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"