我目前正在尝试学习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文件的原因。如果您需要我澄清任何事情,请询问。谢谢! :)
答案 0 :(得分:3)
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.
答案 1 :(得分:0)
存储“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”+密码),而不必担心有两行。