python - 如何让 while 循环识别它是文件结尾

标签 python loops while-loop readline eof

我有一个文本文件,其中的数据表示 1号线 姓名、电子邮件、电话 2号线 地址 3号线 是一个整数,表示列出了多少个 friend 。 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)

friend .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

最佳答案

仅当达到 EOF 时,readline() 方法才返回空字符串 documentation ,因此您可以在调用 readline() 后添加一个条件来检查 line 是否为空(不是 true):

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

关于python - 如何让 while 循环识别它是文件结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53022200/

相关文章:

ruby - 了解 Ruby 中的循环迭代

python - 事件的 Asyncio NotImplementedError

python - 如何从列表中检索单词的位置?

python - 系统路径中安装了多个Python

python - 在多个地方导入相同的模块

javascript - 如何通过递归将重复的字符串/数字推送到newArr?

java - 可能的 Java For 循环问题

c - 循环和函数 :Retirment lab for class

python - 带有矩阵的嵌套循环 - 为什么第二个矩阵呢?

JavaScript while 循环解释