简体   繁体   中英

Python seek() followed by a readline() gives empty string

I am using something similar to the question here:

Python: Undo a Python file readline() operation so file pointer is back in original state

but seems to be misbehaving.

My code: (values at runtime shown as comments)

def parse_shell(self, filename):
    output = None
    with open(self.shells_path + filename) as fp:
        first_line = fp.readline()
# first_line = 'Last login: Tue Jun  9 07:13:26 on ttys0'
        while len(string.split(first_line, '$')) == 1:
            last_pos = fp.tell()
            # last_pos = 43
            first_line = fp.readline()
# first_line =' 2015-06-09 08:18:23 [coryj@Corys-MacBook-Pro ~]$ ping 10.2.2.1'

        fp.seek(last_pos)
        for line in fp.readline():
            # line = ''
            line_chunks = string.split(line, '$')

according to the docs, readline() should only return an empty string if it hits EOF. This particular file is over 200k so I don't see why I would get an empty string.

The problem is that the statement:
while len(string.split(first_line, '$')) == 1: can not be True, so the script never will enter the while loop. string.split() will result in list of minimum two member, like ["some",""] , so len = 2 at least.

Furthermore while loop will run while the statement True , and quits if it turn in to False .

I hope it helped! Feel free to accept my answer if you feel it was useful to you. :-)

like o11c and lawrence said:

for line in fp.readlines() is valid

for line in fp is valid

for line in fp.readline() is not a valid construct.

I don't get what is string.split ? Do you mean str.split ? From what you are trying to do - it looks like - you want to split all lines that have $ in them into parts and ignore other lines. And in your particular case those lines seem to be at the beginning of file. A simpler approach would be

for line in fp:
    if line.find('$') >= 0:
        line.split('$')  # or str.split(line, '$')

Others have pointed out this already, still - line in fp.readlines() is different from line in fp.readline() . Former would iterate over all lines of a file collected in a list, latter will iterate over all characters of only one line.

What you are trying to do is line in fp.readline() is actually trying to iterate over the contents of the line - which is probably not what you want.

' 2015-06-09 08:18:23 [coryj@Corys-MacBook-Pro ~]$ ping 10.2.2.1'

So change it to line in fp (preferred) or line in fp.readlines() . and you should be good

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM