Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a text file using Object-Oriented Programming in Python 3



I am trying to read a text file in Python using a new Class and OOP but I can't find the right way to do it without using imperative programming like this.

def read_operators_file(file_name):
        in_file=open(file_name)
        for i in range(constants.HEADER_TOTAL_LINES):
            in_file.readline()
        operators=[]
        for line in in_file:
            name, nationality, domain, hours, duration = line.strip().split(', ')
            duration=int(duration)
            domain=tuple(domain.strip('(').strip(')').split('; '))
            operators.append((name, nationality, domain, hours, duration))
        in_file.close()
        return operators


def read_requests_file(file_name):
        in_file = open(file_name)
        for i in range(constants.HEADER_TOTAL_LINES):
            in_file.readline()
        requests = []
        for line in in_file:
            name, language, domain, service, duration = line.strip().split(', ')
            duration = int(duration)
            requests.append((name, language, domain, service, duration))
        in_file.close()
        return requests

Thanks,
mikeysantana

like image 871
Miguel Santana Avatar asked Dec 11 '25 18:12

Miguel Santana


1 Answers

While you certainly could convert this to an OOP style, I don't think that it would help much. Instead, I'd suggest trying an FP style. You can define another function, taking the different conversion functions as parameters, e.g. str as basically no-operation, int, or a lambda for more complex stuff. Also, you should use with for opening files.

Something like this (not tested):

def read_fields(file_name, functions):
    with open(file_name) as in_file:
        for i in range(constants.HEADER_TOTAL_LINES):
            in_file.readline()
        result = []
        for line in in_file:
            fields = [f(x) for f, x in zip(functions) line.strip().split(', ')]
            result.extend(fields)
        return result

def read_operators_file(file_name):
    f_domain = lambda d: tuple(d.strip('(').strip(')').split('; '))
    # fields:                    name nat  domain    hrs  dur
    return read_fields(file_name, (str, str, f_domain, str, int))

def read_requests_file(file_name):
    # fields:                    name lang domn serv dur
    return read_fields(file_name, (str, str, str, str, int))

Or using a generator function:

def read_fields(file_name, functions):
    with open(file_name) as in_file:
        for i in range(constants.HEADER_TOTAL_LINES):
            in_file.readline()
        for line in in_file:
            yield from (f(x) for f, x in zip(functions) line.strip().split(', '))
like image 59
tobias_k Avatar answered Dec 14 '25 08:12

tobias_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!