0% found this document useful (0 votes)
3 views18 pages

Python Module4

Module 4 covers file processing and error handling in Python, detailing file operations such as reading, writing, and manipulating files, as well as the importance of closing files and handling exceptions. It emphasizes best practices like using 'with open()' for file operations and provides examples for processing data and managing exceptions. Key points include understanding file modes, processing techniques, and the structure of exception handling.
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)
3 views18 pages

Python Module4

Module 4 covers file processing and error handling in Python, detailing file operations such as reading, writing, and manipulating files, as well as the importance of closing files and handling exceptions. It emphasizes best practices like using 'with open()' for file operations and provides examples for processing data and managing exceptions. Key points include understanding file modes, processing techniques, and the structure of exception handling.
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

Module 4: File Processing and Error Handling

File Operations:

File operations in Python allow you to create, read, write, and manipulate files stored on your
system. They are essential for handling data persistence.

File Input and Output:


File Input and Output (I/O) in Python refers to the process of reading data from files (input)
and writing data to files (output). It is a fundamental concept used in data processing, logging,
and storage.

1. What is File I/O?


*Input→ Reading data from a file
*Output→ Writing data to a file

2. Opening a File
Python uses the built-in open() function:
file = open("[Link]", "mode")

Modes:
* "r" → Read
* "w" → Write (overwrites)
* "a" → Append
* "r+" → Read & Write
* "b" → Binary mode

3. File Input (Reading Data)


# Read entire file
with open("[Link]", "r") as f:
data = [Link]()
print(data)

# Read line by line


with open("[Link]", "r") as f:
for line in f:
print([Link]())

# Read into list


with open("[Link]", "r") as f:
lines = [Link]()
print(lines)

4. File Output (Writing Data)


# Write (overwrite)
with open("[Link]", "w") as f:
[Link]("Hello World\n")

# Append data
with open("[Link]", "a") as f:
[Link]("New line added\n")

# Write multiple lines


lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("[Link]", "w") as f:
[Link](lines)

5. Reading & Writing Together


with open("[Link]", "r+") as f:
content = [Link]()
print(content)
[Link]("\nAdded new content")

6. File Pointer Operations


with open("[Link]", "r") as f:
print([Link]()) # Current position
[Link](0) # Move to start

7. Binary File I/O


# Example: Copying an image
with open("[Link]", "rb") as source:
with open("[Link]", "wb") as target:
[Link]([Link]())

8. Practical Example
# Writing student data
with open("[Link]", "w") as f:
[Link]("Alice,85\nBob,90\n")

# Reading and processing


with open("[Link]", "r") as f:
for line in f:
name, marks = [Link](",")
print(name, "scored", [Link]())

10. Key Points


* Use `with open()` → safer (auto close)
* Choose correct mode
* Handle exceptions
* Useful for real-world tasks like logs, databases, reports

Processing a File:
Processing a File in Python means not just reading or writing, but analyzing, modifying,
filtering, or transforming the data stored in a file.

1. What is File Processing?


File processing involves:
* Reading data from a file
* Performing operations (search, count, modify, filter)
* Writing results back (optional)

2. Basic Steps in File Processing


1. Open the file
2. Read data
3. Process data
4. (Optional) Write results
5. Close file (or use `with`)

3. Example: Counting Words in a File


with open("[Link]", "r") as f:
text = [Link]()
words = [Link]()
print("Total words:", len(words))
4. Example: Counting Lines, Words, Characters
with open("[Link]", "r") as f:
lines = [Link]()
line_count = len(lines)
word_count = 0
char_count = 0

for line in lines:


word_count += len([Link]())
char_count += len(line)

print("Lines:", line_count)
print("Words:", word_count)
print("Characters:", char_count)

5. Example: Searching for a Word


word_to_search = "Python"
with open("[Link]", "r") as f:
for i, line in enumerate(f, start=1):
if word_to_search in line:
print(f"Found in line {i}: {[Link]()}")

6. Example: Copying Content (Processing + Output)


with open("[Link]", "r") as source:
with open("[Link]", "w") as target:
for line in source:
[Link](line)
7. Example: Filtering Data

👉 Write only lines containing a keyword


keyword = "error"
with open("[Link]", "r") as f, open("[Link]", "w") as out:
for line in f:
if keyword in line:
[Link](line)

8. Example: Modifying File Content

👉 Convert all text to uppercase


with open("[Link]", "r") as f:
content = [Link]()
modified = [Link]()
with open("[Link]", "w") as f:
[Link](modified)

9. Example: Processing CSV-like Data


with open("[Link]", "r") as f:
for line in f:
name, marks = [Link](",")
if int(marks) > 80:
print(name, "is a top scorer")

10. Example: Removing Blank Lines


with open("[Link]", "r") as f:
lines = [Link]()
with open("[Link]", "w") as f:
for line in lines:
if [Link](): # skip empty lines
[Link](line)
11. Key File Processing Techniques
* Counting → lines, words, characters
* Searching → keywords
* Filtering→ select specific data
* Transforming → uppercase, lowercase
* Aggregating → sums, averages

Reading from a File:


Reading from a File means retrieving data stored in a file so your program can use or process it.

1. Opening a File for Reading


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

* "r" → read mode (default)


* Error occurs if file does not exist

👉 Best practice:
with open("[Link]", "r") as file:
# operations

2. Methods to Read a File


1. read() – Read Entire File

with open("[Link]", "r") as file:


content = [Link]()
print(content)
✔ Reads full file as a single string

✔ Not ideal for very large files

2. read(size) – Read Specific Characters

with open("[Link]", "r") as file:


print([Link](10)) # reads first 10 characters

3. readline() – Read One Line

with open("[Link]", "r") as file:


line = [Link]()
print(line)

✔ Reads one line at a time

✔ Useful in loops

4. readlines() – Read All Lines as List

with open("[Link]", "r") as file:


lines = [Link]()
print(lines)

✔ Each line becomes an element in a list

5. Reading Using Loop (Best for Large Files)


with open("[Link]", "r") as file:
for line in file:
print([Link]())

✔ Memory efficient

✔ Recommended for large files

3. Example Program
with open("[Link]", "r") as file:
for line in file:
name, marks = [Link](",")
print(name, "scored", [Link]())

4. File Pointer Concept


with open("[Link]", "r") as file:
print([Link](5))
print([Link]()) # current position
[Link](0) # go back to start

5. Key Points
* Always use "r" mode for reading
* Prefer `with open()` (auto close)
* Use loops for large files

Closing a File:

Closing a File in Python is an important step after performing file operations. It ensures that:

 Data is properly saved


 Resources (memory) are released
 File is no longer in use by the program
1. Using close() Method
file = open("[Link]", "r")
# perform operations
[Link]()

✔ This manually closes the file

✔ After closing, the file cannot be used unless reopened

2. Why Closing a File is Important


* Prevents data loss
* Frees system resources
* Avoids file corruption
* Ensures changes are written to disk

3. Checking if File is Closed


file = open("[Link]", "r")
print([Link]) # False
[Link]()
print([Link]) # True

4. Using `with` Statement (Best Practice)


with open("[Link]", "r") as file:
content = [Link]()
print(content)

✔ Automatically closes the file after the block ends

✔ No need to call `close()` manually


5. What Happens if You Don’t Close a File?
* File remains open in memory
* May cause memory leaks
* Changes may not be saved properly

6. Example Program
file = open("[Link]", "w")
[Link]("Hello Python")
[Link]()

# Trying to use closed file

# [Link]("New data") ❌ Error

7. Key Points
* Always close files after use
* Prefer `with open()` for safety
* Avoid working on a closed file

Creating and Writing New Files:


Creating and Writing New Files involves generating a new file (if it doesn’t exist) and storing
data into it.

1. Creating a New File


Python provides modes that automatically create files:

✅ "w" mode (Write)


* Creates a new file if it doesn’t exist
* Overwrites if file already exists
with open("[Link]", "w") as f:
[Link]("This is a new file.")

✅ "x" mode (Exclusive Creation)


* Creates a new file

* ❌ Gives error if file already exists

with open("[Link]", "x") as f:


[Link]("File created successfully")

2. Writing to a File

✅ Using write()

with open("[Link]", "w") as f:


[Link]("Hello Python\n")
[Link]("File handling example")

✔ Writes string data

✔ Does not automatically add newline (`\n` must be used)

✅ Using writelines()

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]

with open("[Link]", "w") as f:


[Link](lines)
✔ Writes multiple lines

✔ Must include `\n` manually

3. Appending to an Existing File


with open("[Link]", "a") as f:
[Link]("\nThis is appended content")

✔ Adds data at the end

✔ Does not overwrite existing content

4. Example Programs

📌 Example 1: Create and Write Student Data

with open("[Link]", "w") as f:


[Link]("Alice,85\n")
[Link]("Bob,90\n")
[Link]("Charlie,78\n")

📌 Example 2: Create File and Write User Input

with open("[Link]", "w") as f:


name = input("Enter your name: ")
[Link]("Name: " + name)

📌 Example 3: Write Numbers to File


with open("[Link]", "w") as f:
for i in range(1, 6):
[Link](str(i) + "\n")

5. Important Points
* "w" → create + overwrite
* "x" → create only (safe mode)
* "a" → append data
* Always use `with open()` (auto close)
* Use `\n` for new lines

6. Common Errors
* Writing to a file opened in "r" mode
* Forgetting newline → data appears in one line
* File already exists when using "x" mode

Exception Handling:

1. What is an Exception?
An exception is an error that occurs during program execution and disrupts the normal flow of
the program.

✅ Examples:
* Division by zero
* File not found
* Invalid input

print(10 / 0) # ZeroDivisionError
2. Types of Errors
1. Syntax Errors
* Occur due to incorrect syntax

if x == 10 # Missing colon

2. Runtime Errors (Exceptions)


* Occur during execution

a = int("abc") # ValueError

3. Defining Exceptions
In Python, exceptions are predefined classes. Some common ones:
* ZeroDivisionError
* ValueError
* TypeError
* FileNotFoundError
* IndexError

4. Dealing with Exceptions (try-except)


Used to handle errors and prevent program crash.

try:
x = int(input("Enter number: "))
y = 10 / x
print(y)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input")

5. Multiple Exceptions in One Block


try:
a = int(input())
b = int(input())
print(a / b)
except (ValueError, ZeroDivisionError):
print("Error occurred")

6. `else` Clause
Executes if no exception occurs.

try:
x = int(input())
print(10 / x)
except ZeroDivisionError:
print("Error")
else:
print("Success")

7. `finally` Clause
Always executes (used for cleanup operations like closing files).
try:
f = open("[Link]")
except FileNotFoundError:
print("File not found")
finally:
print("Execution completed")

8. Using Exceptions (`raise` Keyword)


Used to manually trigger an exception*

age = int(input("Enter age: "))

if age < 18:


raise ValueError("Age must be 18 or above")

9. User-Defined Exceptions
You can create your own exceptions by inheriting from `Exception`.

✅ Example:
class InvalidAgeError(Exception):
pass
age = int(input("Enter age: "))
if age < 18:
raise InvalidAgeError("Not eligible")

10. Handling User-Defined Exception


class InvalidMarks(Exception):
pass
try:
marks = int(input("Enter marks: "))

if marks < 0 or marks > 100:


raise InvalidMarks("Marks should be between 0 and 100")

print("Valid marks")

except InvalidMarks as e:
print("Error:", e)

11. Advantages of Exception Handling


* Prevents program crash
* Improves readability
* Handles unexpected situations
* Ensures smooth program flow

12. Key Points to Remember


* Use `try-except` to handle errors
* Use `finally` for cleanup
* Use `raise` to generate exceptions
* Create custom exceptions when needed
* Always handle specific exceptions when possible

13. Short Summary


* Exceptions are runtime errors
* Handled using `try-except`
* `else` runs if no error
* `finally` always runs
* `raise` is used to generate exceptions
* Custom exceptions are user-defined

You might also like