簡體   English   中英

讀取python中的最后一行后,返回文件的開頭

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

我想逐行讀取文件,但是在讀取了最后一行之后,它應該返回到文件的開頭。

這是我的代碼:

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

此函數批量返回文件的n行。 但是,它應該連續返回到文件的開頭,以便我可以一遍又一遍地讀取批處理。 那么,如何使readline重新開始?

感謝您的時間!

第一次閱讀后,您可以嘗試使用self.f2.seek(0) 這會將偏移位置設置為0。

您必須查找文件的開頭。

因此,在您的情況下,我認為該文件是self.f2 ,因此您必須使用:

self.f2.seek(0)

您應該檢查一下readline()返回的內容。 如果返回空字符串,則可以返回文件的開頭。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM