我希望能够打印文本文件中以特定汽车牌照号码开头的每一行,但我的函数只打印出我想要的牌照号码,如果牌照号码在第一行
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)发布于 2021-01-08 21:29:22
您必须将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() 发布于 2021-01-08 23:03:08
您的原始代码不起作用,因为for line in file:循环在循环的第一行执行rows = file.readlines()。使用readlines,您可以读取文件中的所有内容,因此for循环不会重复,因为没有更多的内容需要读取。使用for循环或readlines。在这种情况下,您应该首选for循环,因为它会遍历文件,并且不需要在内存中包含文件的完整内容。
我假设您的代码在一个名为history的函数中,如果没有找到匹配项,您会尝试再次调用它。这不是一个好的方法(我甚至要说它是一个非常糟糕的方法),因为你会得到递归调用。
如果您希望在找到之前要求用户提供许可证号,则应该使用while True循环。这个循环会一直重复下去,直到您执行break为止。
在这里,我们遍历文件中的所有行,并打印匹配的行。如果找到匹配项,我们将标志found设置为True。当在文件上的循环结束时,我们检查这个标志,并中断外部的while循环。如果我们没有找到匹配,程序将要求一个新的许可证号码。
while True:
which_car = input("Please write your license number: ")
found = False
with open("data", "r") as file:
for line in file:
if line.startswith(which_car):
found = True
print(line)
if found:
break
print("Please write the license number of an existing car! ")如果您希望用户在大多数情况下输入错误的车牌,那么readlines可能是一种替代方案。在这种情况下,您应该在循环开始之前读取该文件,这样就不必每次都这样做。
with open("data", "r") as file:
license_numbers = file.readlines()
while True:
which_car = input("Please write your license number: ")
found = False
for line in license_numbers:
if line.startswith(which_car):
found = True
print(line)
if found:
break
print("Please write the license number of an existing car! ")https://stackoverflow.com/questions/65629819
复制相似问题