简体   繁体   English

python 2.7从文本文件读取多行

[英]python 2.7 read multiple line from text file

I have started to learn python, and have the question below. 我已经开始学习python,并在下面提出了问题。 Please advise. 请指教。

CZ:xxx
CZ:yyy
CZ:zzz
PD:EOL
CZ:uuu
CZ:vvv
CZ:www 
PD:EOL 

how to read the line show individually 如何阅读单行显示

CZ:xxx
CZ:yyy
CZ:zzz
PD:EOL

I tried the below coding. 我尝试了下面的编码。

with open('test.txt','r') as f
    for line in f:
        if 'CZ' in line:
            print line
            break

but only show the first line.... help 但只显示第一行。...帮助

You have added break , which is not required. 您已添加break ,这不是必需的。

with open('test.txt','r') as f
    for line in f:
        if 'CZ' in line:
            print line

Ouput: 输出继电器:

CZ:xxx
CZ:yyy
CZ:zzz

If you want to display first 4 lines use enumerate 如果要显示前4行,请使用枚举

with open('test.txt', 'r') as f
    for index, line in enumerate(f):
        if index < 4 and 'CZ' in line:
            print line
            continue
        break

You can also use str.startswith 您也可以使用str.startswith

Ex: 例如:

with open(filename,'r') as f:
    for line in f:
        if line.startswith("CZ"):
            print line

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM