[英]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. 此函数批量返回文件的n行。 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? 那么,如何使readline重新开始?
Thank you for your time! 感谢您的时间!
You can probably try self.f2.seek(0)
after you read it the first time. 第一次阅读后,您可以尝试使用self.f2.seek(0)
。 This will set the offset position to 0. 这会将偏移位置设置为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
,因此您必须使用:
self.f2.seek(0)
you should check what readline()
returns. 您应该检查一下readline()
返回的内容。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.