簡體   English   中英

如果其中一個以特定字符串開頭,則在Python中讀取連續兩行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM