【问题标题】:How to get the while loop to recognise it is the end of the file如何让while循环识别它是文件的结尾
【发布时间】:2018-10-27 13:10:42
【问题描述】:

我有一个文本文件,其中的数据代表 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

【问题讨论】:

  • 我更新了标题,我的具体问题是 END_OF_FILE .. 它想循环回到开头。除了在开始时进行测试 if lineCount 之外,还有其他方法可以阻止这种情况的发生吗

标签: python loops while-loop readline eof


【解决方案1】:

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

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

【讨论】:

  • 使用第二个建议我跳过了第一行
  • 我只需要在调用循环后删除 --> line = infile.readline() .. 为您的帮助人员提供 TY :-)
  • 如果您要使用第二种方法,请确保删除您的第一个line = infile.readline()
【解决方案2】:

你可以使用

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

而不是 while 循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 2012-12-23
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多