简体   繁体   English

如果其中一个以特定字符串开头,则在Python中读取连续两行

[英]Reading two consecutive lines in Python if one starts with a specific string

I am currently trying to learn Python. 我目前正在尝试学习Python。 I know some basics and I'm trying to practise by making a game. 我知道一些基础知识,我正在尝试通过制作游戏进行练习。 My code so far is: 到目前为止,我的代码是:

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 + '.')

As you probably noticed I am working on a login system. 您可能已经注意到,我正在使用登录系统。 Now please ignore all the bugs and inefficient code etc. I want to focus on how I can get Python to check for a line in a .txt file and, if it's there, check the one below. 现在,请忽略所有错误和效率低下的代码等。我想重点介绍如何让Python检查.txt文件中的一行,如果有,请检查下面的一行。 My .txt file is: 我的.txt文件是:

loggn
pass
__________

I want to make the program multi-account. 我想使该程序具有多个帐户。 This is why I am using a .txt file. 这就是为什么我使用.txt文件的原因。 If you need me to clarify anything, please ask. 如果您需要我澄清任何事情,请询问。 Thankyou! 谢谢! :) :)

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.

Store the results of "open('accounts.txt').read()" yourself, and iterate over them as an array - if you know what line number you are on, it is trivial to check the next. 自己存储“ open('accounts.txt')。read()”的结果,并以数组的形式对其进行迭代-如果您知道所使用的行号,则检查下一个行很简单。 Assuming that every even numbered line is a login, and every odd numbered line is a password, you would have something like this: 假设每条偶数行都是一个登录名,而每条奇数行都是一个密码,您将具有以下内容:

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')

You may also consider changing your file format: using something that won't occur in the login name (such as a colon, unprintable ASCII character, tab, or similar) followed by the password for each line means you could use your original approach by just checking for (login + "\\t" + password) for each line, rather than having to worry about having two lines. 您还可以考虑更改文件格式:使用登录名中不会出现的内容(例如冒号,不可打印的ASCII字符,制表符或类似名称),然后输入每行的密码,这意味着您可以通过以下方式使用原始方法:只需为每行检查(登录+“ \\ t” +密码),而不必担心会有两行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM