import and store - only reading last line

Hello!

I am trying to read from a file and input the values from the file into my class. However, it is only taking the last line. How can I get it to do all of the lines in the file, which is five?

Text File :
231,1200,1,1
232,1250,2,1
233,1300,2,1.5
234,1350,2,2
235,1375,3,2

[code]dataFile = open('apartmentData.txt')
for line in dataFile:
    lineData = line.split(',')
    apt1 = int(lineData[0])
    rent1 = float(lineData[1])
    rooms1 = float(lineData[2])
    baths1 = float(lineData[3])
    
apt_1= Apartments.Apartments(apt1,rent1,rooms1,baths1)
apt_2= Apartments.Apartments(apt1,rent1,rooms1,baths1)
apt_3= Apartments.Apartments(apt1,rent1,rooms1,baths1)
apt_4= Apartments.Apartments(apt1,rent1,rooms1,baths1)
apt_5= Apartments.Apartments(apt1,rent1,rooms1,baths1)

print(apt_1.getApt())
print(apt_2.getApt())
print(apt_3.getApt())
print(apt_4.getApt())
print(apt_5.getApt())

Open in new window


output:
235        1375.0     3.0        2.0      
235        1375.0     3.0        2.0      
235        1375.0     3.0        2.0      
235        1375.0     3.0        2.0      
235        1375.0     3.0        2.0  

desired output:
231        1200.0     1.0        1.0      
232        1250.0     2.0        1.0      
233        1300.0     2.0        1.5      
234        1350.0     2.0        2.0      
235        1375.0     3.0        2.0  [/code]
L WardAsked:
Who is Participating?
 
Olaf DoschkeSoftware DeveloperCommented:
I endorse what gelonida said, you even create variables apt_1 to apt_5 and then only make use of them for print(). You can't loop a list of variables var1 to var6, you can loop all elements of a list, that's why you'd never create var1 to var5, just to save typing brackets. You don' write brackets when you do a for var in list and work with var as the name of the currently picket list element. That's even shorter, isn't it?

As you continue to work with the list, you can also print(aptList[n].getApt()), In your code, you also address aptlist[1] to aptlist[3] in every check, so you compare filter criteria to attributes of the three different apartments 1-3. This way you mix things up totally. Besides counting starts at 0, but it all gets most simple if you loop and then have one apartment at hand in a simple variable without any index or number in its name a loop like for var in list iterates all list elements and copies each one into a simple variable called var. What var is depends on what elements the list hast. In your case likely objects, it could even be further lists, because a list can also be a list of list.

You want to check against every apartment, so you loop over all of them, you address one of them within loop body code, and that shrinks down your code to 1/5th. (think about having 100 apartments, would you really care to write and maintain 100 times almost the same code?).

Well, in short just look at gelonida's code.

Bye, Olaf.
0
 
Olaf DoschkeSoftware DeveloperCommented:
Indentation is pythons way of knowing where the loop body ends. You get the same output 5 times, as all the variables apt1,rent1,rooms1,baths1 only have the last set of values read in from the last line of your txt file. And while you have apt_1 to apt_5, all of them are set with the same values of apt1,rent1,rooms1,baths1.

What you need is:

dataFile = open('apartmentData.txt')
for line in dataFile:
    lineData = line.split(',')
    apt = int(lineData[0])
    rent = float(lineData[1])
    rooms = float(lineData[2])
    baths = float(lineData[3])
    apartment = Apartments.Apartments(apt,rent,rooms,baths)
    print(apartment.getApt())

Open in new window

0
 
gelonidaCommented:
you might also want to keep a list of all the created appartment This is basically Olaf's code with a few more lines.

I also added a second for loop to 'show', that you first read all apartments, store them in a list and that you can then iterate through your list.

dataFile = open('apartmentData.txt')
apartment_list = []
for line in dataFile:
    lineData = line.split(',')
    apt = int(lineData[0])
    rent = float(lineData[1])
    rooms = float(lineData[2])
    baths = float(lineData[3])
    apartment = Apartments.Apartments(apt,rent,rooms,baths)
    apartment_list.append(apartment) # just add it to the end of the list

#  now you can iterate through the list or pass the variable apartment_list to other functions.
for apartment in apartment_list:
        print(apartment.getApt())

Open in new window


Also a small comment about coding style. It is not that important, but makes it easier to exchange coded with other python coders.
So just ignore it if you don't care.

Contrarily to java file names in Python are normally in all lowercase letters with '_' as word separator, so the file containing the the definition of the class Apartment would normally be called apartment.py and you would therefore have lines like
import apartment
apartment.Apartment

Open in new window


usually  variable names are not written in camel case like dataFile or lineData. You see more often more names like data_file and line_data.
classes on the other hand are mostly written in camel case like  class ApartmentInfo or WebServer.

As I said before it has no impact on the functionality of the code, but code is sometimes easier to read if some guide lines are followed. One of the most common python coding style guidelines is PEP http://legacy.python.org/dev/peps/pep-0008/
If you're interested, just look at it it can give you some ideas.
1
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

 
L WardAuthor Commented:
Hi !
Hate to trouble you further, but even though it is a list it seems I cannot index it so I am having trouble storing into 5 seperate objects. Is there a way to get it not just to print, but to be in the apt_1, apt_2 etc. objects so that I can call apt_1 and have it contain all the variables of the class?
0
 
Olaf DoschkeSoftware DeveloperCommented:
You will be able to address apartment_list[0] to apartment_list[5], theyapartmentain apartment objects, to get at the data you want you'll neeed to address apartment_list[0].getApt() to apartment_list[5].getApt()

Bye, Olaf.
0
 
Olaf DoschkeSoftware DeveloperCommented:
You will be able to address apartment_list[0] to apartment_list[5], they're apartment objects. Tto get at the data you want you'll neeed to address apartment_list[0].getApt() to apartment_list[5].getApt().

Or you change the code apartment_list.append(apartment) to apartment_list.append(apartment.getApt()), then apartment_list[0] to apartment_list[5] will be what you wanted without the getApt() call, as that already is done and you store the result of it in the apartment_list elements.

Bye, Olaf.
1
 
gelonidaCommented:
You might check out following link, that explains how lists are working in python.
http://www.diveintopython.net/native_data_types/lists.html

I attached a small example, that's probably not explaining better than above link, but perhaps it's useful

mylist = ["first", "second", "third"] # create a list with three elements
print("list has ", len(mylist), elements) # should print out 3
print("The first element is", mylist[0])
print("The second element is", mylist[1])
print("The third  element is", mylist[2])

mylist.append('fourth') # append an element
print("list has ", len(mylist), elements) # should print out 4

print("The last  element is", mylist[-1])
print("The second last  element is", mylist[-2])

for element in mylist:
    print(element)

for number, element in enumerate(mylist):
    print("element", number, "is", element)

Open in new window

0
 
L WardAuthor Commented:
Thanks the list info helped! I understand this is getting annoying so feel free not to respond, but I thought I got it to work but now the rest of the code isn't working. It keeps printing the whole list every time, and not just the apts that meet the if scenarios.
dataFile = open('apartmentData.txt')
aptList = []
for line in dataFile:
    lineData = line.split(',')
    apt = int(lineData[0])
    rent = float(lineData[1])
    rooms = float(lineData[2])
    baths = float(lineData[3])
    apartment = Apartments.Apartments(apt,rent,rooms,baths)
    aptList.append(apartment)
    
apt_1=aptList[0].getApt()
apt_2=aptList[1].getApt()
apt_3=aptList[2].getApt()
apt_4=aptList[3].getApt()
apt_5=aptList[4].getApt()

while True:
    rentInput=int(input('Enter maximum amount of rent: '))
    roomInput=int(input('Enter minimum number of bedrooms: '))
    bathInput=int(input('Enter minimum number of baths: '))
    try:
        val = int(rentInput)
        val2 = int(roomInput)
        val3 = int(bathInput)
        if val < 0:  
            print("Sorry, input must be a positive integer, try again")
            continue
        if val2 < 0:  
            print("Sorry, input must be a positive integer, try again")
            continue
        if val3 < 0:  
            print("Sorry, input must be a positive integer, try again")
            continue
        break
    except ValueError:
        print("Sorry, input must be a positive integer, try again")


header=True

if header == True:
    print ('{:10} {:10} {:10} {:10}'.format('Aparment#','Rent','Rooms','Bathrooms'))

if rentInput>=aptList[1].rent and roomInput<=aptList[2].rooms and bathInput<= aptList[3].bath:
    print(apt_1)
    
if rentInput>=aptList[1].rent and roomInput<=aptList[2].rooms and bathInput<= aptList[3].bath:
    print(apt_2)
    
if rentInput>=aptList[1].rent and roomInput<=aptList[2].rooms and bathInput<= aptList[3].bath:
    print(apt_3)
    
if rentInput>=aptList[1].rent and roomInput<=aptList[2].rooms and bathInput<= aptList[3].bath:
    print(apt_4)
    
if rentInput>=aptList[1].rent and roomInput<=aptList[2].rooms and bathInput<=aptList[3].bath:
    print(apt_5)

else:
    print('Sorry, no rooms available that meet that criteria')
    header = False

Open in new window

0
 
gelonidaCommented:
The whole point of lists is, that you can use loops and do not have to repeat commands over and over again.
So you don't have to use the vars apt_1 apt_2, . . . anymore. Just  use aptList[0], aptList[1] instead or use a for loop.


So you can remove lines 12 to 16

and replace lines 45 to 62 with something like (as I don't have the code of Appartment.py I'm not 100% sure)

match_count = 0 # counts how many solutions/matches  you found
for apt in aptList:
    if rentInput >= apt.rent and roomInput <= apt.rooms and bathInput <= apt.bath:
        print(apt.getApt())
        match_count += 1
    
if match_count == 0:
    print('Sorry, no rooms available that meet that criteria')
    header = False

Open in new window


As you see, the code became shorter, you have less repetitions and it would be easy to handle hundreds of appartments (as many entries as apartmentData.txt contains lines)
1
 
L WardAuthor Commented:
Thank you both!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.