Home > database >  Not sure what is causing index error in my code
Not sure what is causing index error in my code

Time:02-11

I am working on a small project which is intended to read, create, and manipulate virtual to-do lists. There is a checkbox class, a function open_create_boxes to create a list of checkbox objects based on the contents of a plaintext file, and a function create_to_do_list_file to write a file which can be read by the other function.

# Define the checkbox class
class checkbox:
    def __init__(self,label):
        self.label = label
        self.checked = False
    def check(self):
        self.checked = True
    def read(self):
        if self.checked:
            return f"x | {self.label}"
        if not self.checked:
            return f"o | {self.label}"

def open_create_boxes(file):
    # Open the to-do list
    opened_list = open(f"{file}.dat", "r")
    #Split the to-do list by line
    parsed_line = opened_list.read().split("\n")
    next_parsed = []
    # Split each element in parsed list by the pipe symbol
    for i in parsed_line:
        next_parsed.append(i.split("|"))
    to_do_list = []
    # Iterates through the new list, creates checkbox object, checks to see if it is "checked" or not
    for i in next_parsed:
        b = checkbox(i[1])
        if i[0] == "x":
            b.check()
        to_do_list.append(b)
    return to_do_list

def create_to_do_list_file(list,label):
    # Open or create a file label.dat
    new_file = open(f"{label}.dat", "w")
    for n in list:
        new_file.write(f"\no|{n}")

create_to_do_list_file(["Task"],"filename")
open_create_boxes("filename")

Running this code gives me the error:

  File "/home/genie/Desktop/checkboxes/checkboxes.py", line 41, in <module>
    open_create_boxes("filename")
  File "/home/genie/Desktop/checkboxes/checkboxes.py", line 28, in open_create_boxes
    b = checkbox(i[1])
IndexError: list index out of range

So something is going wrong in my open_create_boxes function, where the list is coming out with <2 elements. I have re-written this code several times and get the same, or similar, errors.

Any help here? I'm a beginner, so I imagine there's an obvious fix, but I can't seem to manage.

Thanks!!

CodePudding user response:

Quickly running your code and examining the created file reveals that its first line is empty. Of course you will only get one field if you attempt to split that. Why are you writing \n in front of the data?

Similarly, your code to read the file fails to account for the empty line, whether at the beginning or the end of the file.

More tangentially, you are forgetting to close the file you write, and generally overcomplicate matters.

Here is a quick refactoring of the two file-management functions.

def open_create_boxes(file):
    to_do_list = []
    with open(f"{file}.dat", "r") as lines:
        for line in lines:
            i = line.rstrip("\n").split("|")
            # print("#", i)
            b = checkbox(i[1])
            if i[0] == "x":
                b.check()
            to_do_list.append(b)
    return to_do_list

# Don't call your variable "list"
def create_to_do_list_file (items ,label):
    with open(f"{label}.dat", "w") as new_file:
        for n in items:
            new_file.write(f"o|{n}\n")

As a general first tip for how to debug things, break your problem into smaller steps and add a print statement at various points to verify that the variables contain what you hope they should, or use a debugger and set a breakpoint to examine the program's state at those spots.

  • Related