如何解决我想在我的文本文件中打印以特定许可证号开头的行,但仅当许可证号在第一行时才会打印出来
我希望能够打印文本文件中以特定汽车牌照号码开头的每一行,但如果牌照号码在第一行,我的函数只会打印出我想要的牌照号码
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)
解决方法
您必须将 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()
,
您的原始代码不起作用,因为您的 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! ")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。