2013-04-15 40 views
0

我正在一個項目上工作,遇到了麻煩。請記住我是初學者程序員。如何從兩點之間的文本文件打印信息?

我想要做的就是打印是在文本文件中,兩點之間的信息。

我的代碼:

AccountName=input("What Is The Name Of The Account Holder?") 

Accounts=open("Accounts.txt", "r") 
lines = Accounts.readlines() 
Accounts.close 

for i, line in enumerate(lines): 
    if AccountName in line: 
     print(line) 

文本文件:

Alex Peters Aken South Carolina Citizens Bank 865074 $25,000 09/25/2013 12401 (845)545-5555 Joe Small Albany New York Key Bank 763081 $4,800 10/15/2013 24503 (845)734-5555 說我想從 「喬小」 打印到(845)734-5555 我會怎麼做呢?

(無該信息是真實的)

回答

0

你可以爲(在Python3)

line_index = 0 
while line_index < len(lines): 
    if AccountName in lines[line_index]: 
     for line in lines[line_index:line_index+9]: 
      print(line, end="") 
     line_index += 9 
    else: 
     line_index += 1 

在Python 2.X改變for循環,打印一句話應該是:

print line, 
+0

謝謝@Sheng你的回答讓我得到最後的結果我一直在尋找! – user2280738

+0

@ user2280738我很高興看到我的代碼可以幫助其他人! – Sheng

+0

@ user2280738不要忘記[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – John

1

如果您知道該線路,並且您使用了.readlines,那麼您可以找到所需的子列表:

sublines = lines[lines.index('Joe Small'):lines.index('(845)734-5555')+1] 

然後,您可以打印該列表中的每一行。

但是請注意,如果有列表中的多個唯一的行這種做法是行不通的。

我會採取的做法更像是:

startLine = 'Joe Small' 
endLine = '(845)734-5555' 

shouldPrint = False 

for line in f: 
    line = line.strip() 
    if shouldPrint: 
     print line 

    if line == startLine: 
     shouldPrint = True 
    elif line == endLine: 
     shouldPrint = False 
0

我個人很喜歡SAPI的解決方案,

Accounts=open("file.txt", "r") 
lines = Accounts.readlines() 
lines = [line.strip() for line in lines] 
Accounts.close() 

accounts = zip(*[iter(lines)]*9) 

for account in accounts: 
    if "Joe Small" in account: 
     print account 
相關問題