![](/img/trans.png)
[英]How do I read a file line by line and print the line that have specific string only in python?
[英]python read file, print part of line that begins with a specific string
我有一個包含以下內容的文本文件
steve:789852:1
sean:1234:1
我想讀取文件,並且用戶輸入的內容與名字匹配,然后打印出中間數字。 我可以只執行一行,而不能繼續執行其余的操作
IndexError: list index out of range
我已經嘗試過for循環和while循環。 我正在使用的代碼如下。 任何幫助請
x = 0
username = input('enter user name ')
file = open('user_details.txt', 'r')
count = len(open('user_details.txt').readlines())
while x < count:
print(x)
userFile = file.read().split('\n')[x]
userArray = userFile.split(':')
if (userArray[0] == username):
print('password = '+userArray[1])
x = x+1
python中通常不需要循環索引變量,而只需使用for循環即可。 一個好的經驗法則是,當您知道將要進行多少次迭代時,請使用for循環;而當您不知道時應使用一段時間。
username = input('enter user name ')
with open('user_details.txt', 'r') as f:
for line in f:
userArray = line.strip().split(':')
if (userArray[0] == username):
print('password = '+userArray[1])
請注意,該文件僅打開一次,也可以使用with
塊正確關閉。 它也只迭代文件本身的行一次。
代碼的關鍵問題是,在while循環的第一次迭代之后,將文件耗盡。
目的是讀取文件的每一行,但是您要做的是對文件的行進行計數並循環多次,然后在每個迭代中讀取整個文件。 在兩次迭代之間不會重新打開該文件,因此,第一次while循環迭代該文件直到結束為止。 當您在while的第二次迭代中再次出現時,沒有什么要讀取,因此您嘗試獲取該空列表的1索引,因此出現索引錯誤。
它偶然地對第一個起作用,因為所有行的列表中都有第0個元素。
readlines()
將文件指針指向文件末尾。 因此,當您嘗試使用相同的文件引用再次讀取文件時,將返回一個空字符串。 將內容讀入變量並在循環中對其進行迭代。
無論使用
for line in file.readlines():
... do stuff ...
或使用
lines = file.read().split('\n')
for line in lines:
... do stuff ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.