Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

python - I want to print the line in my textfile that starts with a specific license number, but this only prints out if the license number is in the 1st line

I want to be able to print every line in my textfile that starts with a specific car license number, but my function only prints out the license number I want if the license number is in the first line

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You must put the which_car outside the loop. Also, from my understanding, you want to print all lines that begin with the number provided and if there is no line that begins with that number, then only in that case you will print the alternative message. If this is what you want, try the following. You would better add it in a function, so that it will run every time user inputs a new licence number:

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

Version 2: Using a function:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...