[英]Converting a text file to list and then reading list to determine if an entry is within the list
將文本文件轉換為列表時遇到了一些麻煩。 文本文件顯示如下:
5658845
4520125
7895122
8777541
8451277
1302850
8080152
我編寫了接受用戶輸入並嘗試確定用戶輸入是否在列表中的代碼。 但是,我在搜索列表時遇到了一些麻煩,因為我只能從列表中的最后一個結果中獲取結果,我在哪里出錯?
def accountReader():
while True:
chargeInput = (raw_input ("Enter a charge account to be validated: "))
if chargeInput == '':
break
sys.exit
else:
chargeAccount = open('charge_accounts.txt', 'r')
line = chargeAccount.readline()
while line != '':
if chargeInput == line:
print chargeInput, 'was found in list.'
else:
print chargeInput, 'not found in list.'
break
chargeFile.close
我會這樣閱讀清單
chargeAccount = open('charge_accounts.txt', 'r')
accts = [line.strip() for line in chareAccount]
if chareInput in accts:
#do something
else:
#do something else
至少在readline()的.strip()處,您的行可能看起來像是“ 5658845 \\ n”
UPDATE
因此,在測試了我的修改后,它可以正常工作....除了它對while acct重復indef!=''
這是我改變的
chargeAccount = open('charge_accounts.txt', 'r')
accts = [line.strip() for line in chargeAccount]
while accts != '':
if chargeInput in accts:
#...
我完全放棄了while循環,它要么在列表中,要么不在列表中。 無需在每一行中循環。
逐行細分:
def accountReader():
while True:
chargeInput = (raw_input ("Enter a charge account to be validated: "))
if chargeInput == '':
break
sys.exit
好的,到目前為止很好。 您已經創建了一個循環,該循環反復詢問用戶輸入內容,並在用戶未輸入任何內容時中斷。
else:
chargeAccount = open('charge_accounts.txt', 'r')
line = chargeAccount.readline()
這是您開始遇到問題的地方。 readline
從chargeAccount
讀取一行並將其存儲在line
。 這意味着您只能測試一條線!
while line != '':
if chargeInput == line:
print chargeInput, 'was found in list.'
這進一步加劇了您的問題。 如果chargeInput == line
,則打印一條消息,然后循環重復。 由於沒有任何問題可以打破循環,因此將導致無限循環,不斷測試文件中的一行。 另外,由於文件中的每一行都以換行符( \\n
)結尾, chargeInput == line
始終產生false(感謝Steven Rumbalski提醒我這一點)。 使用.strip()
(根據matchw的答案中的建議),或者,如果您可以容忍部分匹配,則可以使用Python的簡單子字符串匹配功能: if chargeInput in line
。
else:
print chargeInput, 'not found in list.'
break
chargeFile.close
正如sarnold所指出的,您在這里給文件起了錯誤的名字。 此外,它位於完全不同的代碼塊中,這意味着您反復打開chargeAccount
文件而不關閉它們中的任何一個。
從matchw的帖子中可以看到,有一種簡單得多的方法可以完成您想做的事情。 但是,我認為您會很好地弄清楚如何以所選的樣式正確編寫此代碼。 我給你一個提示:應該有一個line = chargeAccount.readline()
最里面的while循環中 。 你明白為什么嗎? 同樣,您應該在成功找到匹配項時退出循環,而不是在失敗時退出循環。 然后,您應該考慮一種方法,以測試最內層循環完成后搜索是否成功。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.