Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read next line in Python

Tags:

python

I am trying to figure out how to search for a string in a text file, and if that string is found, output the next line.

I've looked at some similar questions on here but couldn't get anything from them to help me.

This is the program I have made. I have made it solely to solve this specific problem and so it's also probably not perfect in many other ways.

def searcher():
    print("Please enter the term you would like the definition for")
    find = input()
    with open ('glossaryterms.txt', 'r') as file:
        for line in file:
            if find in line:
                print(line)

So the text file will be made up of the term and then the definition below it.

For example:

Python
A programming language I am using

If the user searches for the term Python, the program should output the definition.

I have tried different combinations of print (line+1) etc. but no luck so far.

like image 539
user1480135 Avatar asked Nov 22 '15 10:11

user1480135


People also ask

How do you read the next line of a text file in Python?

Python File next() Method Python file method next() is used when a file is used as an iterator, typically in a loop, the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit.

How do you go to the next line in Python?

Newline character in Python: In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line.

How read a string from line by line in Python?

Python readline() method reads only one complete line from the file given. It appends a newline (“\n”) at the end of the line. If you open the file in normal read mode, readline() will return you the string. If you open the file in binary mode, readline() will return you binary object.

How do you read multiple lines in a text file in Python?

To read multiple lines, call readline() multiple times. The built-in readline() method return one line at a time. To read multiple lines, call readline() multiple times.


4 Answers

your code is handling each line as a term, in the code below f is an iterator so you can use next to move it to the next element:

with open('test.txt') as f:
    for line in f:
        nextLine = next(f)
        if 'A' == line.strip():
            print nextLine
like image 55
Paweł Kordowski Avatar answered Oct 21 '22 08:10

Paweł Kordowski


If your filesize is small, then you may simply read the file by using readlines() which returns a list of strings each delimited by \n character, and then find the index of the selected word, and the print the item at position + 1 in the given list.

This can be done as:

def searcher():
    print("Please enter the term you would like the definition for")
    find = input()

    with open("glossaryterms.txt", "r") as f:       
        words = list(map(str.strip, f.readlines()))
        try: 
            print(words[words.index(find) + 1])
        except:
            print("Sorry the word is not found.")
like image 40
ZdaR Avatar answered Oct 21 '22 08:10

ZdaR


You could try it Quick and dirty with a flag.

with open ('glossaryterms.txt', 'r') as file:
  for line in file:
    if found:
        print (line)
        found = False
    if find in line:
        found = True

It's just important to have the "if found:" before setting the flag. So if you found your search term next iteration/line will be printed.

like image 44
Ben Avatar answered Oct 21 '22 10:10

Ben


In my mind, the easiest way would be to cache the last line. This means that on any iteration you would have the previous line, and you'd check on that - keeping the loop relatively similar

For example:

def searcher():
    last_line = ""
    print("Please enter the term you would like the definition for")
    find = input()
    with open ('glossaryterms.txt', 'r') as file:
        for line in file:
            if find in last_line:
                print(line)
            last_line = line
like image 20
meiamsome Avatar answered Oct 21 '22 08:10

meiamsome