如何在两点之间打印文本文件中的信息?

2024-04-24 03:45:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个项目,遇到了麻烦。 请记住,我是一个初学者程序员。你知道吗

我要做的是打印文本文件中两点之间的信息。你知道吗

我的代码:

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 假设我想从“Joe Small”打印到(845)734-5555 我该怎么做?你知道吗

(这些信息都不是真实的)


Tags: the项目代码in信息line程序员small
3条回答

如果您知道所讨论的行,并且使用了.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

您可以将for循环更改为(在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

在Python2.X中,print语句应该是:

print line,

我个人喜欢萨皮的解决方案

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

相关问题 更多 >