简体   繁体   中英

Return to the beginning of a file after reading last line in python

I want to read a file line by line, but after reading the last line it should return to the beginning of the file.

Here is my code:

def readLabels(self, n):
    resline = np.empty([0,2])
    for i in range(0,n):
        line = (self.f2.readline()).split(',')
        line = [x for x in line if is_number(x)]
        line = [float(s) for s in line]
        line = np.asarray(line)
        resline = np.concatenate((resline, [line]),axis=0)
    return resline

This function returns n lines of the file as a batch. However, it should continuously return to the beginning of the file, so that I can read batches over and over again. So how can I make readline return to the beginning?

Thank you for your time!

You can probably try self.f2.seek(0) after you read it the first time. This will set the offset position to 0.

You have to seek the beginning of the file.

So in your case I think the file is self.f2 , thus you have to use:

self.f2.seek(0)

you should check what readline() returns. If it returns empty string, then you can go back to the beginning of the file.

def readLabels(self, n):
    resline = np.empty([0,2])
    for i in range(0,n):
        line = self.f2.readline()
        if not line:
            # back to top
            self.f2.seek(0)
            # read again
            line = self.f2.readline()
        line = line.split(',')
        line = [x for x in line if is_number(x)]
        line = [float(s) for s in line]
        line = np.asarray(line)
        resline = np.concatenate((resline, [line]),axis=0)
    return resline

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