Python- Day 34- Simplifying Data Storage and Exception Handling in Python

Nidhi Ashtikar
3 min readJan 8, 2025

--

Storing data is a crucial aspect of programming, and one of the simplest ways to do so is by writing to a file. This allows you to preserve program output even after the program ends, enabling data sharing and later reuse. This article explores various techniques for writing files in Python, including handling exceptions and working with multiple files.

Writing a Single Line

The write_text() method from Python's pathlib module makes it easy to write data to a file. Here's a simple example:

from pathlib import Path

path = Path('programming.txt')
path.write_text("I love programming.")

How It Works:

  • Creating the File: If programming.txt doesn't exist, write_text() creates it.
  • Writing Data: The string "I love programming." is written to the file.
  • Output: Open programming.txt to see the text.

Note: Python writes strings to text files. To store numbers, use the str() function to convert them.

Writing Multiple Lines

To write multiple lines, build a single string containing all lines and include newline characters (\n) for separation:

from pathlib import Path

contents = "I love programming.\n"
contents += "I love creating new games.\n"
contents += "I also love working with data.\n"

path = Path('programming.txt')
path.write_text(contents)

Result in programming.txt:

I love programming.
I love creating new games.
I also love working with data.

Tip: Be cautious with write_text(). It overwrites the file if it already exists.

Handling User Input and Writing to Files

Example 1: Writing a Single Name

name = input("What's your name? ")
path = Path('guest.txt')
path.write_text(name)

Example 2: Collecting Names in a Loop

from pathlib import Path

path = Path('guest_book.txt')

while True:
name = input("Enter your name (or 'q' to quit): ")
if name.lower() == 'q':
break
with path.open(mode='a') as file:
file.write(f"{name}\n")

File Output (guest_book.txt):

Alice
Bob
Charlie

Handling Exceptions

Preventing Crashes with try-except

Errors like dividing by zero or missing files can halt your program. Use try-except blocks to handle them gracefully.

Example: Handling Division by Zero

try:
print(5 / 0)
except ZeroDivisionError:
print("You can't divide by zero!")

Example: Handling Missing Files

from pathlib import Path

path = Path('nonexistent_file.txt')

try:
contents = path.read_text()
except FileNotFoundError:
print(f"Sorry, the file {path} does not exist.")

Analyzing Text Files

Text analysis often involves counting words in a file. Here’s an example that counts words in “Alice in Wonderland”:

from pathlib import Path

path = Path('alice.txt')

try:
contents = path.read_text(encoding='utf-8')
except FileNotFoundError:
print(f"Sorry, the file {path} does not exist.")
else:
words = contents.split()
print(f"The file {path} has about {len(words)} words.")

Output:

The file alice.txt has about 29594 words.

Working with Multiple Files

You can extend the above example to analyze multiple files by iterating through a list of filenames:

from pathlib import Path

def count_words(filename):
path = Path(filename)
try:
contents = path.read_text(encoding='utf-8')
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist.")
else:
words = contents.split()
print(f"The file {filename} has about {len(words)} words.")

filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename)

Output:

The file alice.txt has about 29594 words.
Sorry, the file siddhartha.txt does not exist.
The file moby_dick.txt has about 215864 words.
The file little_women.txt has about 189142 words.

Failing Silently

To ignore missing files without interrupting program execution, use the pass statement:

try:
contents = path.read_text()
except FileNotFoundError:
pass

Python makes file handling simple and versatile. Whether you’re writing single lines, handling exceptions, or analyzing text, Python’s file handling capabilities provide robust tools for data management. With practice, you can build efficient programs that handle user input, errors, and data storage seamlessly.

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