python - 我想在我的文本文件中打印以特定许可证号开头的行,但这仅在许可证号在第一行时才会打印出来
问题描述
我希望能够打印我的文本文件中以特定车牌号开头的每一行,但是如果许可证号在第一行,我的函数只会打印出我想要的许可证号
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()
推荐阅读
- react-native - 如何使用 create-react-native-app Metro 捆绑器进行配置
- jquery - 重构表
- java - 如何让 GitHub 操作给我一个 jar 文件而不是 zip?
- postgresql - 如何在 Scala 中使用环境变量和 application.conf 文件?
- matlab - 如何插入 3D 数据的时间和速度?
- c# - 将 WebClient 代码转换为 HttpClient 代码
- javascript - 未捕获的类型错误:无法在“TextDecoder”上执行“解码”:提供的值不是“(ArrayBuffer 或 ArrayBufferView)”类型
- uri - 生成临时 URI
- regex - Ansible:仅当是最新版本时才安装包
- javascript - 将两个数组之间的差异推入一个新数组