When you do : f.readlines() you already read all the file so f.tell() will show you that you are in the end of the file, and doing f.next() will result in a StopIteration error.

Alternative of what you want to do is:

filne = "D:/testtube/testdkanimfilternode.txt"

with open(filne, 'r+') as f:
    for line in f:
        if line.startswith("anim "):
            print f.next() 
            # Or use next(f, '') to return <empty string> instead of raising a  
            # StopIteration if the last line is also a match.
            break
Answer from mouad on Stack Overflow
๐ŸŒ
Dot Net Perls
dotnetperls.com โ€บ readline-python
Python - readline Example: Read Next Line - Dot Net Perls
# Open the file. f = open(r"C:\programs\info.txt", "r") while(True): # Read a line. line = f.readline() # When readline returns an empty string, the file is fully read. if line == "": print("::DONE::") break # When a newline is returned, the line is empty. if line == "\n": print("::EMPTY LINE::") continue # Print other lines.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ file_next.htm
Python File next() Method
# Open a file fo = open("foo.txt", ... 4 - This is 5th line ยท Let us now try to use the alternative for this method, the readline() method, for Python 3.x....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ read-a-file-line-by-line-in-python
Read a File Line by Line in Python - GeeksforGeeks
3 weeks ago - A file object can be directly iterated using a for loop. Each iteration reads the next line from the file, allowing the contents to be processed line by line.
๐ŸŒ
YouTube
youtube.com โ€บ codesolve
how to read next line in python - YouTube
Instantly Download or Run the code at https://codegive.com title: reading next line in python: a step-by-step tutorialintroduction:reading the next line in ...
Published ย  February 23, 2024
Views ย  10
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 42136707 โ€บ reading-the-next-line-in-a-text-document
python - reading the next line in a text document - Stack Overflow
you can hold your previous line in a helper string. (note, I'm using previous/current instead of current/next) dclist = [] interface = "" vrfmem = "" db = sqlite3.connect('data/main.db') cursor = db.cursor() cursor.execute('''SELECT r1 FROM routers''') all_rows = cursor.fetchall() for row in all_rows: dclist.append(row[0]) for items in dclist: f = open('data/'+ items + '.txt', 'r+') currLine = f.readline() while line != '': prevLine = currLine currLine = f.readline() if 'interface Vlan' in prevLine : interface = re.search(r'(?<=\interface Vlan).*', line).group(0) if 'vrf member' in currLine: vrfmem = interface = re.search(r'(?<=\vrf member).*', line).group(0) else: vrfmem = "default" if 'ip address' in prevLine: print(items + interface + vrfmem + "ip her" ) db.commit() db.close()
Find elsewhere
Top answer
1 of 2
2

Here's what you are trying to do, and probably could have gotten there with a little debugging.

temp_keywords = ''
mykeywords = ''
with open(input_file, encoding="utf8") as fo:    
    for line in fo:
        if line[:2].isupper():    
            if line[:2] == 'GJ':
                temp_line = line[2:].strip()
                next_line = next(fo)
                temp_line += next_line.strip()
                print (temp_line.split(';'))

The problem here is that calling next(fo) yourself, instead of letting the for loop do its job, means you have to handle all of the for loop's job. So whatever you read into next_line will NOT be processed on the next loop. You will completely miss some lines of the file.

Instead, you always want to let the for loop handle its job.

But what you have here is two different methods of breaking a file up. It's easier to write a record parser which finds full records, and let it read lines from the file as needed. Here is an adaptation of my other answer linked in comments:

def is_new_record(line):
    return line[:2].isupper()

def helper(text):
    data = []
    for line in text.readlines():
        if is_new_record(line):
            if (data):
                yield ''.join(data)
            data = [line.strip()]
        else:
            data.append(line.strip())
    if (data):
        yield ''.join(data)

# the helper is a generator for multiline records, as one line
input_file = 'data.txt'
with open(input_file) as f:
    for record in helper(f):
        print (record)

LA English
DT Article
GJ asthma; susceptible genes; natural language processing analysis; networkcentrality analysis
ID LITERATURE-BASED DISCOVERY; CO-WORD ANALYSIS; UNDISCOVERED PUBLICKNOWLEDGE; INFORMATION-RETRIEVAL; FISH-OIL; SCIENTIFIC COLLABORATION;INSULIN-RESISTANCE; COMPLEX NETWORKS; METFORMIN; OBESITY
GJ natural language processing; network analysis
GJ data mining; text mining; learning analytics; deep learning;network centrality analysis

2 of 2
1

Let's try spliting the problem. There are two main logic processes in your code:

  1. Extract each non-indented row with the following indented rows and join them as a single "line".
  2. Filter "GJ" initial lines only.

Here is the code:

def iter_lines(fo):
    cur_line = []
    for row in fo:
        if not row.startswith(' ') and cur_line:
            yield ' '.join(cur_line)
            cur_line = []  # reset the cache
        cur_line.append(row.strip())
    # yield the last line
    if cur_line:
        yield ' '.join(cur_line)


with open(input_file, encoding="utf8") as fo:
    for line in iter_lines(fo):
        if line.startswith('GJ'):
            keywords = [k.strip() for k in line[2:].split(';')]
            print(keywords)
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-read-text-file-line-by-line
How to read File Line by Line in Python?
Following are the steps to read file line by line using readline() function. Read file in text mode. It returns a stream to the file. Create an Infinite While Loop. During each iteration of the loop, read the next line from the file using readline().
๐ŸŒ
Python
python-list.python.narkive.com โ€บ 2vKatk2x โ€บ how-do-i-peek-into-the-next-line
how do I "peek" into the next line?
I want to just "peek" in to the next line, and if it starts with a special character I want to break out of a for loop, other wise I want to do readline(). Is there a way to do this? line=stdin.peek_nextline() if not line: break x=stdin.nextline() # do something with x thanks -- http://mail.python.org/mailman/listinfo/python-list Well what you can do is read the line regardless into a testing variable.
๐ŸŒ
Guru99
guru99.com โ€บ home โ€บ python โ€บ python readline() method with examples
Python readline() Method with Examples
1 month ago - ๐Ÿ“„ Read One Line: file.readline() returns the next line including the newline character at the end. ๐Ÿ“ Size Argument: Pass a byte limit to readline to cap how much of the line is returned.
Top answer
1 of 3
3

You don't need to call next(). You are already iterating over the lines of the file, so, don't do anything, and the next line will come at the next iteration.

elif clientid not in line:
    pass

Unrelated to file reading: You if-elseif-else doesn't make sense. clientid in line is either true or false, so it doesn't make sense to have 3 conditions. Just remove the middle elif altogether`

2 of 3
2

for loop already calls next for you.

Since you are reading a csv file (a file with values separated by commas) you should use the csv module - it automatically splits each line for you, so you don't have to slice each line yourself.

To further help you I also removed the globals and used parameter passing to pass the variable to the other function. Also I removed the recursive call to main() and used a loop to repeat the search. If you enter the empty string (just press enter), it should exit the loop and finish the program.

import csv

def main():
    print("===================")
    print("=Activity Recorder=")
    print("===================")

    while True:
        clientid=input("Please enter the client ID: ")
        print("")
        if not clientid:
             break
        with open ("clientIntensity.txt") as f:
            search = csv.reader(f, delimiter=',')
            for row in search:
                if row[0] == clientid:
                    idin = row[1]
                    print ("Intensity = ", idin)
                    acti(idin)
                    break
            else:
                print('ERROR: Not found')

def acti(idin):
    if idin == "High":
        print("Activites = Running, Swimming, Aerobics, Football, Tennis")
    elif idin == "Moderate":
        print("Activities = Walking, Hiking, Cleaning, Skateboarding, Basketball")
    else:
        print("ERROR: Unknown idin")
๐ŸŒ
Python Reference
python-reference.readthedocs.io โ€บ en โ€บ latest โ€บ docs โ€บ file โ€บ next.html
next โ€” Python Reference (The Right Way) 0.1 documentation
This method returns the next input ... to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the next() method uses a hidden read-ahead buffer....
Top answer
1 of 6
6

If you just want to skip over lines not starting with #, there's a much easier way to do this:

file_handler = open(fname, 'r')
    for line in file_handler:
       if line[0] != '#':
           continue
       # now do the regular logic
       print line

Obviously this kind of simplistic logic won't work in all possible cases. When it doesn't, you have to do exactly what the error implies: either use iteration consistently, or use read methods consistently. This is going to be more tedious and error-prone, but it's not that bad.

For example, with readline:

while True:
    line = file_handler.readline()
    if not line:
        break
    if line[0] == '#':
        print line
    else:
        line2 = file_handler.readline()
        print line2

Or, with iteration:

lines = file_handler
for line in file_handler:
    if line[0] == '#':
        print line
    else:
        print line
        print next(file_handler)

However, that last version is sort of "cheating". You're relying on the fact that the iterator in the for loop is the same thing as the iterable it was created from. This happens to be true for files, but not for, say, lists. So really, you should do the same kind of while True loop here, unless you want to add an explicit iter call (or at least a comment explaining why you don't need one).

And a better solution might be to write a generator function that transforms one iterator into another based on your rule, and then print out each value iterated by that generator:

def doublifier(iterable):
    it = iter(iterable)
    while True:
        line = next(it)
        if line.startswith('#'):
            yield line, next(it)
        else:
            yield (line,)
2 of 6
1
file_handler = open(fname, 'r')
for line in file_handler:
   if line.startswith('#'): # <<< comment 1
       print line
   else:
       line2 = next(file_handler) # <<< comment 2
       print line2

Discussion

  1. Your code used a single equal sign, which is incorrect. It should be double equal sign for comparison. I recommend to use the .startswith() function to enhance code clarity.

  2. Use the next() function to advance to the next line since you are using file_handler as an iterator.