Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a text file has another line Python

Tags:

python

I'm working on a script to parse text files into a spreadsheet for myself, and in doing so I need to read through them. The issue is finding out when to stop. Java has a method attached when reading called hasNext() or hasNextLine() I was wondering if there was something like that in Python? For some reason I can't find this anywhere.

Ex:

open(f) as file:
    file.readline()
    nextLine = true
    while nextLine:
        file.readline()
        Do stuff
        if not file.hasNextLine():
            nextLine = false
like image 221
yourknightmares Avatar asked Jul 16 '26 08:07

yourknightmares


2 Answers

Just use a for loop to iterate over the file object:

for line in file:
    #do stuff..

Note that this includes the new line char (\n) at the end of each line string. This can be removed through either:

for line in file:
    line = line[:-1]
    #do stuff...

or:

for line in (l[:-1] for l in file):
    #do stuff...

You can only check if the file has another line by reading it (although you can check if you are at the end of the file with file.tell without any reading).

This can be done through calling file.readline and checking if the string is not empty or timgeb's method of calling next and catching the StopIteration exception.

So to answer your question exactly, you can check whether a file has another line through:

next_line = file.readline():
if next_line:
    #has next line, do whatever...

or, without modifying the current file pointer:

def has_another_line(file):
    cur_pos = file.tell()
    does_it = bool(file.readline())
    file.seek(cur_pos)
    return does_it

which resets the file pointer resetting the file object back to its original state.

e.g.

$ printf "hello\nthere\nwhat\nis\nup\n" > f.txt
$ python -q
>>> f = open('f.txt')
>>> def has_another_line(file):
...     cur_pos = file.tell()
...     does_it = bool(file.readline())
...     file.seek(cur_pos)
...     return does_it
... 
>>> has_another_line(f)
True
>>> f.readline()
'hello\n'
like image 65
Joe Iddon Avatar answered Jul 18 '26 22:07

Joe Iddon


The typical cadence that I use for reading text files is this:

with open('myfile.txt', 'r') as myfile:

    lines = myfile.readlines()

for line in lines:

    if 'this' in line: #Your criteria here to skip lines
        continue

    #Do something here

Using with will only keep the file open until you have executed all of the code within it's block, then the file will be closed. I also think it's valuable to highlight the readlines() method here, which reads all lines in the file and stores them in a list. In terms of handling newline (\n) characters, I would point you to @Joe Iddon's answer.

like image 22
rahlf23 Avatar answered Jul 18 '26 22:07

rahlf23