0

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

Edited by epicSHOOTER236

3
Contributors
7
Replies
122
Views
3 Years
Discussion Span
Last Post by epicSHOOTER236
1

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']

Edited by Gribouillis

0

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'.

Edited by snippsat

0

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

1

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

Edited by snippsat

0

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)

Edited by epicSHOOTER236

0

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>.

0

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()

Edited by epicSHOOTER236

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.