Hi everyone,

I am trying to create a list of objects in python. I get the listing of all of the files from the directory that I want. Then I open each file and read it into an appropriate object and append it to the list. For some reason when the data gets read in from the file it gets appended to the end of the last file. So by the end, the last object contains all of the previous objects. Here is my code:

"""
    Reads in all of the room_tables and adds them to the room_tables list
    """
    def get_room_tables(self):
        cur_dir = os.getcwd()
        cur_dir = cur_dir + "/room_tables"

        count = 0
        file_list = []
        for filename in os.listdir(cur_dir):
            if 'table' in filename:
                filename = cur_dir + '/' + filename
                file_list.insert(count, filename)
                count += 1

        for file in file_list:
            new_table = RoomTable()
            new_table.read_from_file(file)
            self.room_tables.append(new_table)
            print new_table.room_table

and the method it calls:

"""
    Reads in a room_table from a file
    @param room_table: file to be read from
    """
    def read_from_file(self,room_table):
        if room_table is not None:
            file = open(room_table, 'r')
            file_list = file.readlines()
            
            self.class_name = file_list[0].rstrip('\n')

            count = 1
            while count in range(len(file_list)):
                line = file_list[count].split()
                self.room_table.append(line)
                count += 1

Thanks

Recommended Answers

All 2 Replies

What is your problem? What is purpose of overriding the file type? Why are you using count when you append to list all lines splitted? How is RoomTable initialized? You are passing file name, call the string file. You are using it as filename string and override built in type with the filehandle... Sorry I do not understand the purpose of all this. Why not only read and split the lines normaly?

The problem here is not getting records from the file. The problem is that you have large blocks of untested code. I am adding one print statement and a list declaration as a hint:

def read_from_file(self,room_table):
        if room_table is not None:
            fp = open(room_table, 'r')
            file_list = fp.readlines()
            fp.close()
            self.room_table = []         ## <----- start with an empty list each time
            self.class_name = file_list[0].rstrip('\n')
 
            for rec in range(1, len(file_list)):
                line = rec.split()
                self.room_table.append(line)
        print self.room_table
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.