如何获取while循环以识别它是文件的结尾

时间:2018-10-27 13:10:42

标签: python loops while-loop readline eof

我有一个文本文件,其数据表示 1号线 姓名,电子邮件,电话 2号线 地址 3号线 是一个整数,表示列出了多少个朋友。 4号线〜n 每行包含一个名称

我已经获得了每一行

line = infile.readline()

到达文件末尾时出现问题。

它想再次循环,好像它无法识别文件的结尾

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

2 个答案:

答案 0 :(得分:1)

仅当documentation达到EOF时,readline()方法才返回空字符串,因此您可以添加条件以检查line是否为空(不真实)。致电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])

或者,您可以将文件对象用作带有for循环的迭代器:

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

答案 1 :(得分:1)

您可以使用

for line in infiles.readline():
    *code*

代替while循环。