Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在两点之间打印文本文件中的信息?_Python - Fatal编程技术网

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

Python 如何在两点之间打印文本文件中的信息?,python,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 AccountNam

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

我要做的是在两点之间打印文本文件中的信息

我的代码:

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)
文本文件:


亚历克斯·彼得斯
阿肯
南卡罗来纳州
公民银行
865074
$25,000
09/25/2013
12401
(845)545-5555
乔·斯莫尔
奥尔巴尼
纽约
密钥库
763081
$4,800
10/15/2013
24503
(845)734-5555
假设我要从“Joe Small”打印到(845)734-5555 我该怎么做


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

您可以将for循环更改为(在Python3中)


如果您知道有问题的行,并且使用了
.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

我个人喜欢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

谢谢@Sheng你的回答帮助我得到了我想要的最终结果@user2280738别忘了。@johnthexii有时候,提问者会得到答案,然后离开,永远不要投票或接受任何答案。
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
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