[英]Reading two consecutive lines in Python if one starts with a specific string
我目前正在尝试学习Python。 我知道一些基础知识,我正在尝试通过制作游戏进行练习。 到目前为止,我的代码是:
import time
import datetime
now = datetime.datetime.now()
name = input('What is your name? >> ')
file = open("users.txt","+w")
file.write(name + ' started playing at: ' + now.strftime("%Y-%m-%d %H:%M") + '. \n')
file.close()
account = input('Do you have an account ' + name + '? >> ')
while(account != 'yes'):
if(account == 'no'):
break
account = input('Sorry, I did not understand. Please input yes/no >> ')
if(account == 'yes'):
login = input('Login >>')
passwd = input('Password >>')
if login in open('accounts.txt').read():
if passwd in open('accounts.txt').read():
print('Login Successful ' + login + '!')
else:
print('Password incorrect! The password you typed in is ' + passwd + '.')
else:
print('Login incorrect! The login you typed in is ' + login + '.')
您可能已经注意到,我正在使用登录系统。 现在,请忽略所有错误和效率低下的代码等。我想重点介绍如何让Python检查.txt文件中的一行,如果有,请检查下面的一行。 我的.txt文件是:
loggn
pass
__________
我想使该程序具有多个帐户。 这就是为什么我使用.txt文件的原因。 如果您需要我澄清任何事情,请询问。 谢谢! :)
with open('filename') as f:
for line in f:
if line.startswith('something'):
firstline = line.strip() # strip() removes whitespace surrounding the line
secondline = next(f).strip() # f is an iterator, you can call the next object with next.
自己存储“ open('accounts.txt')。read()”的结果,并以数组的形式对其进行迭代-如果您知道所使用的行号,则检查下一个行很简单。 假设每条偶数行都是一个登录名,而每条奇数行都是一个密码,您将具有以下内容:
success = False
# Storing the value in a variable keeps from reading the file twice
lines = open('account.txt').readlines()
# This removes the newlines at the end of each line
lines = [line.strip() for line in lines]
# Iterate through the number of lines
for idx in range(0, len(lines)):
# Skip password lines
if idx % 2 != 0:
continue
# Check login
if lines[idx] == login:
# Check password
if lines[idx + 1] == password:
success = True
break
if success:
print('Login success!')
else:
print('Login failure')
您还可以考虑更改文件格式:使用登录名中不会出现的内容(例如冒号,不可打印的ASCII字符,制表符或类似名称),然后输入每行的密码,这意味着您可以通过以下方式使用原始方法:只需为每行检查(登录+“ \\ t” +密码),而不必担心会有两行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.