Python- Day 33- Mastering File Handling and Exception Management in Python

Nidhi Ashtikar
4 min readJan 1, 2025

--

Working with files and handling exceptions are essential skills for creating robust and user-friendly Python programs. This article explores the fundamentals of file handling, reading content, working with file paths, and using exception handling to ensure stability. We’ll include detailed code examples and outputs to give you hands-on insights.

Why Work with Files and Exceptions?

  1. Enable programs to analyze large datasets, store user data, and ensure continuity between sessions.
  2. Help manage errors gracefully, preventing programs from crashing during unexpected scenarios.

With these skills, you can make your programs more relevant, robust, and user-friendly.

Reading from Files

Reading files is one of the most common tasks in programming. Let’s start with the basics.

from pathlib import Path

# Create a Path object for the file
path = Path('pi_digits.txt')

# Read the file content
contents = path.read_text()

# Display the file content
print(contents)

Output:

3.1415926535
8979323846
2643383279

What’s Happening?

  • Path('pi_digits.txt') creates a path to the file.
  • read_text() reads the entire file content and returns it as a string.

Removing Extra Whitespace

Files often contain unwanted whitespace. Use the rstrip() method to clean up the output.

from pathlib import Path

path = Path('pi_digits.txt')
contents = path.read_text().rstrip() # Remove trailing whitespace
print(contents)

Output:

3.1415926535
8979323846
2643383279

Reading Files Line by Line

When working with large files, you might want to process each line individually.

from pathlib import Path

path = Path('pi_digits.txt')
contents = path.read_text()
lines = contents.splitlines() # Split content into individual lines

for line in lines:
print(line)

Output:

3.1415926535
8979323846
2643383279

Key Concept: splitlines() creates a list of lines from the file content, which can then be processed one at a time.

Concatenating File Lines

Combine lines from a file into a single string for easier analysis.

from pathlib import Path

path = Path('pi_digits.txt')
contents = path.read_text()
lines = contents.splitlines()

pi_string = '' # Initialize an empty string
for line in lines:
pi_string += line.strip() # Remove leading/trailing spaces and concatenate

print(pi_string)
print(len(pi_string)) # Print the length of the resulting string

Output:

3.141592653589793238462643383279
32

What’s Happening?

  • Each line is stripped of whitespace and added to pi_string.
  • The resulting string contains all digits of pi with no spaces.

Handling Missing Files

Robust programs don’t crash when files are missing. Use exception handling to manage this gracefully.

from pathlib import Path

path = Path('missing_file.txt')

try:
contents = path.read_text()
print(contents)
except FileNotFoundError:
print("The file does not exist. Please check the file path.")

Output:

The file does not exist. Please check the file path.

Key Concept: The try-except block ensures the program continues running even when the file is not found.

Practical Applications

Analyzing Large Files

You can process files containing millions of lines or characters without modifying your core logic.

from pathlib import Path

path = Path('pi_million_digits.txt')
contents = path.read_text()
lines = contents.splitlines()

pi_string = ''
for line in lines:
pi_string += line.strip()

# Display the first 50 digits
print(f"{pi_string[:50]}...")
print(len(pi_string)) # Length of the string

Output:

3.14159265358979323846264338327950288419716939937510...
1000002

What’s Happening?

  • The program reads and concatenates lines from a large file.
  • It prints only the first 50 digits for brevity.

Finding Data in Files

Let’s check if a specific date (e.g., a birthday) appears in the digits of pi.

from pathlib import Path

path = Path('pi_million_digits.txt')
contents = path.read_text()
lines = contents.splitlines()

pi_string = ''
for line in lines:
pi_string += line.strip()

birthday = input("Enter your birthday (mmddyy): ")
if birthday in pi_string:
print("Your birthday appears in the first million digits of pi!")
else:
print("Your birthday does not appear in the first million digits of pi.")

Input:

Enter your birthday (mmddyy): 120372

Output:

Your birthday appears in the first million digits of pi!

Key Concept:

  • The program converts file content into a searchable string.
  • Uses the in keyword to check if the birthday is part of the pi digits

By mastering file handling and exception management in Python, you can:

  • Create programs that handle large datasets effectively.
  • Ensure stability with exception handling.
  • Build features that enhance usability, such as saving and searching user data.

With these techniques, you’re well-equipped to create robust, scalable, and user-friendly applications.

If you found this guide helpful then do click on 👏 the button.

Follow for more Learning like this 😊

Let’s connect! Find me on LinkedIn.

If there’s a specific topic you’re curious about, feel free to drop a personal note or comment. I’m here to help you explore whatever interests you!

Thanks for spending your valuable time learning to enhance your knowledge!

--

--

Nidhi Ashtikar
Nidhi Ashtikar

Written by Nidhi Ashtikar

Experienced AWS DevOps professional with a passion for writing insightful articles.

No responses yet