Search code examples
pythonreadlines

readlines is showing up empty after creating file


I am looking to create a file then read the values I just put into it and put those values into a list. I use readlines to do so, however I get the "list assignment index out of range" error which tells me that its not reading the file.

here is my code:

import os

class open_saved_file():

    def __init__(self):
        self.path = os.getcwd()
        self.path_extension = "/Saved_Paths"
        self.file_extension = "/Paths.txt"
        self.paths = []

    def test_path(self):

        test_bool = os.path.exists(self.path+self.path_extension)
#1) path does not exist
        if not test_bool:
            print "The start folder does not exist, let's create it"
            os.makedirs(self.path+self.path_extension)
            print "just made file, now make Paths.txt"
            of = open(self.path+self.path_extension+self.file_extension, 'w+')
            print "Lets add 4 dummy lines of code"
            i = 0
            while i < 4:
                of.write("dummy\n")
                i = i+1
            print "just added four lines of dummy"
            of.close()
            print "lets test"
            self.read_lines_into_list()
            return self.paths
#2) path and file exist
        else:
            print "The start folder did exist, yay!"
            print "lets open it and put its value into paths list"
            self.read_lines_into_list()
            return self.paths

    def read_lines_into_list(self):
        of = open(self.path+self.path_extension+self.file_extension)
        lines = of.readlines()
        self.paths[0] = lines[0][:-1]
        self.paths[1] = lines[1][:-1]
        self.paths[2] = lines[2][:-1]
        self.paths[3] = lines[3][:-1]
        print "lets test if all the values went in"
        j = 0
        while j < 4:
            print self.paths[j]
            i = i+1

Solution

  • The error occurs not because lines is empty, but because self.paths is. Instead of:

    self.paths[0] = lines[0][:-1]
    

    Use append():

    self.paths.append(lines[0][:-1])
    

    You're also going to get an error in your while loop because you're doing a i = i+1 when your loop variable is j. You can simply replace i with j, or even better, use a for loop:

    for path in self.paths:
        print path