首页 > 解决方案 > 我想在我的文本文件中打印以特定许可证号开头的行,但这仅在许可证号在第一行时才会打印出来

问题描述

我希望能够打印我的文本文件中以特定车牌号开头的每一行,但是如果许可证号在第一行,我的函数只会打印出我想要的许可证号

with open("data","r") as file:
    for line in file:
        file.readlines()
        which_car = input("Please write your license number: ")
        if not line.startswith(which_car):
            print("Please write the license number an existing car! ")
            history()
        else:
            print(line)

标签: python

解决方案


您必须将 which_car 放在循环之外。另外,据我了解,您想打印所有以提供的数字开头的行,如果没有以该数字开头的行,那么只有在这种情况下,您才会打印替代消息。如果这是您想要的,请尝试以下操作。您最好将它添加到一个函数中,以便每次用户输入新的许可证号时它都会运行:

with open("data","r") as file:
    rows=file.readlines()
    which_car = input("Please write your license number: ")
    c=0
    for line in rows:
        if line.startswith(which_car):
            print(line)
            c+=1
    if c==0:
        print("Please write the license number of an existing car! ")
        history()

版本 2:使用函数:

def check_licence_number():
    which_car = input("Please write your license number: ")
    c=0
    with open("data","r") as file:
        rows=file.readlines()
        for line in rows:
            if line.startswith(which_car):
                print(line)
                c+=1
        if c==0:
            print("Please write the license number of an existing car!")
            check_licence_number()        
            

推荐阅读