Error handling in python if file written with int instead of string

Viewed 124

I have a code that works and have a simple question. If I were to change the text-file from strings to integer I want to error handle that. Is it possible? I only get error-warning when I change the integers to strings however I want it to work for changing strings to integer. For example if I change "Football" into a integer I want to get a error-warning. I then want to create an error-handling to print for example: "Something is wrong inside the textfile"

textfile:
Football # 8-9 # Pitch
Basketball # 9-10 # Gym
Lunch # 11-12 # Home
Reading # 13-14 # Library


from pprint import pprint
class Activity:
    def __init__(self, name, start_time, end_time, location):
        self.name = str(name)
        self.start = int(start_time)
        self.end = int(end_time)
        self.location = str(location)

 
def read_file(filename):
    activities = []
    with open(filename, 'r') as f:
        for line in f:
            activity, time, location = line.strip().split(' # ')
            start, end = time.split('-')
            activities.append(Activity(activity, start, end, location))
    return activities

activities = read_file('sample.txt')
pprint(activities)
1 Answers

You can check if a string is an integer by using isnumeric.

So let's change the input file to:

Football # 8-9 # Pitch
Basketball # 9-10 # Gym
Lunch # 11-12 # Home
3 # 13-14 # Library

Now we want to verify the name, for which we will write a validator:

class Activity:
    def __init__(self, name, start_time, end_time, location):
        self.name = self.validate_name(name)
        self.start = int(start_time)
        self.end = int(end_time)
        self.location = location

    def validate_name(self, name):
        if name.isnumeric():
            raise TypeError(f"The name: {name!r}, is not a string, please check your input file.")
        return name

    def __repr__(self):
        return f"<{type(self).__name__}, (name={self.name}, start={self.start}, end={self.end}, loc={self.location})>"

Which results in a TypeError:

 line 13, in validate_name
    raise TypeError(f"The name: {name!r}, is not a string, please check your input file.")
TypeError: The name: '3', is not a string, please check your input file.

Note that your input is already a string, so there was no need to use str(name) and str(location).


Edit

The above solution only verifies if the entire name is an integer. For a solution that checks if the input is using valid characters we can use the re module in python and the method:

import re

def validate_input(self, name):
    regex = re.compile('\d')
    if regex.match(name):
        raise TypeError(f"The name: {name!r}, contains an integer, please check your input file.")
    return name

This will break whenever there is an integer in the input name. The previous solution would continue on inputs such as: Football 3, 3 Football. This solution would raise an error.

You can try out the regex expression for yourself on regex101

Related