如何让 while 循环识别它是文件的末尾

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

提问人:Scot Henderson 提问时间:10/27/2018 最后编辑:Scot Henderson 更新时间:10/27/2018 访问量:51

问:

我有一个文本文件,其中包含代表 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 [email protected] 123456789
1 alltheway ave
1
Jane Doe
Paul Andrews [email protected] 987654321
69 best street
0
Jane Doe jane.doe@facebook.com 159753456
1 alltheway ave
2
John Doe
Paul Andrews
python 循环 while 循环 readline eof

评论

0赞 Scot Henderson 10/27/2018
我更新了标题,我的具体问题是END_OF_FILE..它想循环回到起点。如果 lineCount <= totalLines,除了在开始时进行测试之外,还有其他方法可以阻止这种情况发生吗

答:

1赞 blhsing 10/27/2018 #1

该方法仅在根据文档达到 EOF 时返回空字符串,因此您可以在调用后立即添加条件来检查是否为空(不真实):readline()linereadline()

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])

评论

0赞 Scot Henderson 10/27/2018
使用第二个建议,我跳过了第一行
0赞 Scot Henderson 10/27/2018
我只需要在调用循环后删除 --> line = infile.readline() ..为您的帮助人员提供 TY :-)
1赞 blhsing 10/27/2018
如果您要使用第二种方法,请确保删除第一种方法。line = infile.readline()
1赞 dhae 10/27/2018 #2

你可以使用

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

而不是 while 循环。