我尝试在用户从文本文件中输入的代码下打印2行。
我的文字档案:
86947367
banana
5
78364721
apple
3
35619833
orange
2
84716491
sweets
8
46389121
chicken
10
因此,如果用户输入例如46389121
,则会打印
chicken
10
我试过了:
file = 'read_it.txt'
user = input('Enter code')
with open(file, 'r') as f:
lines = f.readlines()
for i, line in enumerate(lines): # enumerate will count and keep track of the lines
if line == user:
print("{}\n{}".format(lines[i+1], lines[i+2]))
但它给了我一个空白行的输出,请帮忙吗?
答案 0 :(得分:0)
在使用rstrip()
进行比较之前尝试剥离线:
file = 'read_it.txt'
user = input('Enter code')
with open(file, 'r') as f:
lines = f.readlines()
for i, line in enumerate(lines): # enumerate will count and keep track of the lines
if line.rstrip() == user:
print("{}\n{}".format(lines[i+1], lines[i+2]))
请记住,您不必一次加载所有文件,而是可以像这样迭代它:
file = 'read_it.txt'
user = input('Enter code')
with open(file, 'r') as f:
for line in f:
if line.rstrip() == user:
print(next(f).rstrip())
print(next(f).rstrip())
break
rstrip()
函数删除字符串末尾的空格。空白包括,
\n
,\t
,\r
等。