简体   繁体   中英

Python - Reading and print between lines ?

I have this code where I'm reading from a plain text

python file:

from itertools import islice

def phones():
    with open('phones.txt','r+') as f:
        lines = islice(f, 2, 4) #lines 2 and 4 only
        for line in f:
            found_phone = line.find('Phone')
            if found_phone != -1:
                Phones = line[found_phone+len('Phone:'):]
                print Phones 
    return Phones

phones()

My problem is I want to print the word next to "Phone" between lines 2 and 4, it's printing every word after "phone" I want only between lines 2 and 4.

This is my text file

First lines of Phones
        Phone Blackberry #Line 2
        Phone iPhone     #Line 3 
        Phone Huawei     #Line 4
Second lines of Phones
        Phone Samsung
        Phone LG

This is my output:

在此处输入图片说明

What I want to print only is between lines 2 and 4 I would like this output:

Blackberry
iPhone
Huawei

I was trying to do it with itertools but it's not working... What am I doing wrong?

There are two issues here. Firstly, you specify lines as your slice, but then loop over the whole file, f . Secondly, your slice won't return what you're after - islice appears to be zero-based and won't include the upper limit (from my tests in Python 2.7) and so the section you're actually after is islice(f, 1, 4) .

The code with these corrections is as follows:

from itertools import islice

def phones():
    with open('phones.txt','r+') as f:
        lines = islice(f, 1, 4)
        for line in lines:
            found_phone = line.find('Phone')
            if found_phone != -1:
                Phones = line[found_phone+len('Phone:'):]
                print Phones 
    return Phones

phones()

This returns

Blackberry

iPhone

Huawei

To remove the lines between the values, you can use print Phones.rstrip() rather than print Phones .

You can try this:

lines = [line.split() for line in open('phones.txt','r+')]
lines = lines [1:4]

select = [x[1] for x in lines ]

output => ['Blackberry', 'iPhone', 'Huawei']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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