Sunday, October 30, 2022

[FIXED] How to get the while loop to recognise it is the end of the file

Issue

I have a text file with data that represents Line 1 name, email, phone Line 2 address Line 3 is an integer that says how many friends are listed. Line 4 ~ n Each line consists of a name

I have been able to get each line with

line = infile.readline()

I have a problem when I get to the end of the file.

It wants to loop around again as if it does not recognise the end of the file

infile = open(filename, "r")
lines = infile.readlines()

with open(filename) as infile:  
        line = infile.readline()
        count = 1
        while line:
            thisProfile = profile.Profile()          
            if count > 1:
                line = infile.readline()
                count += 1
            word = line.split()
            thisProfile.set_given_name(word[0])
            thisProfile.set_last_name(word[0])
            thisProfile.set_email_name(word[0])
            thisProfile.set_phone(word[0])

            ## LINE 2 -- ADDRESS
            line = infile.readline()
            count += 1
            thisProfile.set_address(line)

             ## LINE 3 -- GET FRIEND COUNT
             line = infile.readline()
             count += 1

             ## get all the friends and add them to the friends_list
             friendCount = int(line)
             thisProfile.set_number_friends(friendCount)
             friendList = []
             if friendCount > 0:
                 for allfreinds in range(0,friendCount):
                     line = infile.readline()
                     count += 1
                     friendList.append(line)
                 thisProfile.set_friends_list(friendList)

friends.txt

John Doe john.doe@hotmail.com 123456789
1 alltheway ave
1
Jane Doe
Paul Andrews paul.andrews@gmail.com 987654321
69 best street
0
Jane Doe jane.doe@facebook.com 159753456
1 alltheway ave
2
John Doe
Paul Andrews

Solution

The readline() method returns an empty string only when EOF is reached per the documentation, so you can add a condition to check if line is empty (not truthy) right after you call readline():

with open(filename) as infile:  
    while True:
        line = infile.readline()
        if not line:
            break
        thisProfile = profile.Profile()          
        word = line.split()
        thisProfile.set_given_name(word[0])

Alternatively, you can use the file object as an iterator with a for loop instead:

with open(filename) as infile:  
    for line in infile:
        thisProfile = profile.Profile()          
        word = line.split()
        thisProfile.set_given_name(word[0])


Answered By - blhsing
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.