How would i make python read a text file and find something then read a certian number of lines below it
i.e if you had:

card 1:
    ball
    red

it need to find card 1:, then it needs to read the line below (ball) and set it to a string then read the next line and put it to another string

Recommended Answers

All 7 Replies

If the searched text is in a single line, you can read the file line by line:

import itertools as itt

def wrong_line(line):
    return 'card 1:' not in line

with open('filename.txt') as ifh:
    result = list(itt.islice(itt.dropwhile(wrong_line, ifh), 1, 3))

# result should be the list ['    ball\n', '    red\n']

Alternative to Gribouillis good use of itertools.

search_word = 'card 1'
with open('filename.txt') as f:
    for line in f:
        if search_word in line:
            print 'Next line after: {} is {}'.format(search_word, next(f).strip())
            print next(f).strip()

'''Output-->
Next line after: card 1 is ball
red
'''

You can you next() to jump line for line after you search for 'card 1'.

i dont need it in a list i need bal to be set as a variable so:
top_line = ball
bottom_line = red

i dont need it in a list i need bal to be set as a variable so:
top_line = ball
bottom_line = red

You should have be able to figure this out,with the help you already got.

import itertools as itt

def wrong_line(line):
    return 'card 1:' not in line

with open('filename.txt') as ifh:
    result = list(itt.islice(itt.dropwhile(wrong_line, ifh), 1, 3))

top_line, bottom_line = [i.strip() for i in result]
print top_line #ball
print bottom_line #red

----

search_word = 'card 1'
with open('filename.txt') as f:
    for line in f:
        if search_word in line:
            top_line = next(f).strip()
            bottom_line = next(f).strip()

print top_line #ball
print bottom_line #red

the probelm is the file is alread open through tkFiledialog, and when i use

open(file name) #where it says file name it would be the variable assinged by askopenfile

it says theis function requiers 2 arguments (1 given)

askopenfile() should return an open file object. Use this object for the variable ifh or f above and don't use open(). Your error message for open() is wrong. Try print(open) and check that it prints <built-in function open>.

i used the object and it has somewhat worked but where it says top_line = next(f).strip() it gives me an error saying:

top_line = next(deck_filename_open_2).strip()
TypeError: list object is not an iterator

EDIT: I got it fixed with iter()

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.