【问题标题】:Reading the next line of a text file?读取文本文件的下一行?
【发布时间】:2019-02-03 09:05:03
【问题描述】:

好的,我已经查看了所有其他问题,但我不确定如何将我读到的内容应用到我的代码中,我也不确定它是否会起作用。所以我的文本文件看起来像这样:

NeQua,High,
ImKol,Moderate,
YoTri,Moderate,
RoDen,High,

并且我的代码能够读取第一行并剪切部分,但是当我为第二行添加搜索请求时,它会出现错误。那么如何让它读取下一行呢?

这是我目前的代码:

def main():
    global idin,clientid
    print("===================")
    print("=Activity Recorder=")
    print("===================")
    clientid=input("Please enter the client ID : ")
    print("")
    with open ("clientIntensity.txt") as search:
        for line in search:
            if clientid in line:
                idin=line[6:]#to extract high or moderate from the text
                idin=idin[:-2]
                print ("Intensity = ",idin)
                print("-",idin,"-")
                acti()
                break

            elif clientid not in line:
                search.next()
            else:
                print("Error")
                main()
def acti():
    global idin,clientid
    if idin == "High":
        print("Activites = Running, Swimming, Aerobics, Football, Tennis")
    elif idin == " Moderate ":
        print("Activities = Walking, Hiking, Cleaning, Skateboarding, Basketball")
    else:
        print("error 2")

我不太确定如何使用下一个功能。

【问题讨论】:

  • 为什么你从 main() 调用 main() 而从不调用 main() 本身?

标签: python python-3.x line next


【解决方案1】:

您无需致电next()。您已经在文件的行上进行迭代,所以,不要做任何事情,下一行将出现在下一次迭代中。

elif clientid not in line:
    pass

与文件读取无关:你 if-elseif-else 没有意义。 clientid in line 要么是真要么是假,所以有 3 个条件是没有意义的。把中间的elif 去掉就行了`

【讨论】:

  • @RishabSudhir:谢谢。如果解决了问题,请采纳答案
【解决方案2】:

for 循环已经为你调用了next

由于您正在读取 csv 文件(值由逗号分隔的文件),您应该使用 csv 模块 - 它会自动为您分割每一行,因此您不必自己分割每一行。

为了进一步帮助您,我还删除了全局变量并使用参数传递将变量传递给其他函数。我还删除了对main() 的递归调用,并使用循环重复搜索。如果您输入空字符串(只需按回车键),它应该退出循环并完成程序。

import csv

def main():
    print("===================")
    print("=Activity Recorder=")
    print("===================")

    while True:
        clientid=input("Please enter the client ID: ")
        print("")
        if not clientid:
             break
        with open ("clientIntensity.txt") as f:
            search = csv.reader(f, delimiter=',')
            for row in search:
                if row[0] == clientid:
                    idin = row[1]
                    print ("Intensity = ", idin)
                    acti(idin)
                    break
            else:
                print('ERROR: Not found')

def acti(idin):
    if idin == "High":
        print("Activites = Running, Swimming, Aerobics, Football, Tennis")
    elif idin == "Moderate":
        print("Activities = Walking, Hiking, Cleaning, Skateboarding, Basketball")
    else:
        print("ERROR: Unknown idin")

【讨论】:

    【解决方案3】:

    行:

    with open ("clientIntensity.txt") as search:
    

    创建一个名为search 的文件对象。这个文件对象有many methods,但没有.next() 方法。因此,调用.next() 会引发类似于“你想让我做什么!?”的错误。


    但是,您确实知道自己想做什么,您想遍历每一行,并且您正在使用 for 循环执行此操作。 for循环的美妙之处在于,在当前迭代结束时,它会自行继续进行下一次迭代,直到到达终点(这个终点实际上是aStopIteration)。

    因此,如果您只想继续下一行,只需让 for 循环滚动!

    with open ("clientIntensity.txt") as search:
        for line in search:
            if clientid in line:
                idin=line[6:]#to extract high or moderate from the text
                idin=idin[:-2]
                print ("Intensity = ",idin)
                print("-",idin,"-")
                acti()
                break
    

    最后一个提示。如果你有一个像hello,there, 这样的字符串,那么通过切片来提取there 需要付出很多努力,但是通过使用string 对象的方法(即.split())很容易做到这一点。这允许您通过指定分隔符来获取子字符串列表。例如,'hello,there,'.split(',') 给出['hello', 'there', '']。然后你可以用'hello,there,'.split(',')[1] 索引第二个词,给出'there'

    注意:split 方法返回第三个元素的原因是字符串以逗号结尾,所以以逗号分割时,也会返回末尾的空字符串,但是你可以忽略这个.

    【讨论】:

    • 哦,非常感谢!这大大简化了我的生活!
    • @RishabSudhir 没问题
    猜你喜欢
    • 2013-11-04
    • 2019-09-05
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多