File Handling and Exception Handling
File Handling in Python
Introduction
File: A named location on disk for storing related information.
Used for permanent data storage in non-volatile memory (e.g. hard disk).
Random Access Memory (RAM) is volatile; files are essential for data persistence.
File Operations
Open a file
Read or write (perform operations)
Close the file
Use the
open()function to open files.
Opening a File
Syntax:
f = open("test.txt")Returns a file object (handle) to read/modify the file.
Closing a File
Use the
close()method when done to free resources.Syntax:
f.close()
Writing to a File
Open in modes:
'w': Write, overwrites existing data.'a': Append, adds to existing data.'x': Exclusive creation, fails if file exists.
Caution:
'w'mode will erase existing content.
Reading from a File
Open in reading mode.
Methods to read:
read(size): read up tosizebytes; ifsizeis not specified, it reads to EOF.
Syntax:
file_object = open(file_name [, access_mode])Access Modes:
r: Read only (default).
rb: Read in binary format.
r+: Read and write.
w: Write only (overwrites existing).
wb: Write in binary format.
a: Append.
ab: Append in binary format.
a+: Append and read.
Reading Methods
read() Method
Syntax:
fileObject.read([count])Reads a specified number of bytes; if no count, reads until EOF.
Example:
fo = open("sample.txt", "r+") str = fo.read(10) print("Read String is: ", str) fo.close()
readlines() Method
Reads until EOF and returns a list of lines.
Returns an empty string when EOF is immediately encountered.
Syntax:
fileObject.readlines(sizehint)
readline() Method
Reads a single line from the file.
File Positions
tell(): Returns current position in the file.seek(offset[, from]): Changes the file position based on offset and reference point.Reference points:
0: Beginning of file1: Current position2: End of file
Writing Data
write() Method
Writes a string to an open file without newline character.
Syntax:
fileObject.write(string)Example:
fo = open("sample.txt", "w") fo.write("Good morning.\nWe are studying File Handling! !\n") fo.close()
File Renaming and Removal
rename() Method
Syntax:
os.rename(current_file_name, new_file_name)
remove() Method
Deletes a file.
Syntax:
os.remove(file_name)
Working with Directories
Directory Operations
Creation: Use
mkdir()method to create a directory.os.mkdir("newdir")Change Directory: Use
chdir()method to change the current directory.os.chdir("newdir")Current Directory: Use
getcwd()to get the current directory.
Removing Directories
rmdir(): Deletes a directory (must be empty).
os.rmdir('dirname')
Exception Handling
Exception Overview
Exception: An event that disrupts the normal flow of a program.
Represents an error in Python.
Handling Exceptions
Use
tryandexceptblocks to handle exceptions:try: # Suspicious operations except ExceptionType: # Handle exception
Syntax of Try-Except
Structure:
try: # Operations except Exception1: # Handle Exception1 except Exception2: # Handle Exception2 else: # Execute if no exceptions occur
Finally Clause
Code block always executed after try block finishes:
try: # Code finally: # Code always runs
Raising Exceptions
Use the
raisestatement to raise exceptions manually.raise ExceptionType("message")
Custom Exceptions
Define custom exceptions by creating a new class inherited from Exception.
Example:
class CustomError(Exception): passRaises using the class just like built-in exceptions.