Search code examples
pythonpython-3.xhardcodehardcoded

How to prevent hardcoding when reading from txt-file to 3 different lists - python


I am creating a code in which it reads information from a txt-file and stores the information on three separate lists. The code I have created does this, but in a pretty hardcoded manner. My question is if there is any better way to read from the file by for example using a for-loop or anything since the code at this point is repeating itself.

The code I have created is:

def load():
with open("kurser.txt") as share_price_time:
    share_price_list_1 = []
    share_price_list_2 = []
    share_price_list_3 = []
    row_number = 0
    for row in share_price_time:
        if 36 < row_number < 67:
            info_1 = row.strip().split("\t")
            share_price_list_1.append(info_1[1])
        elif 104 < row_number < 135:
            info_2 = row.strip().split("\t")
            share_price_list_2.append(info_2[1])
        elif 172 < row_number < 203:
            info_3 = row.strip().split("\t")
            share_price_list_3.append(info_3[1])
        row_number = row_number + 1

Thank you in advance for your help!


Solution

  • You can use itertools.islice to read out those contiguous portions and then process each line into a list which is appended to a parent list:

    from itertools import islice
    
    indices = [(37, 67), (105, 135), (173, 203)]
    
    def load():
       with open("kurser.txt") as share_price_time:
          lst = []
          for st, sp in indices:
             lst.append([r.strip().split("\t")[1] 
                                   for r in islice(share_price_time, st, sp)])
             share_price_time.seek(0)
    

    The list of indices are easily amendable and can easily be passed as part of the function arguments.