开发者

python constructor basic question

开发者 https://www.devze.com 2023-03-08 07:53 出处:网络
I am trying to reuse an opened file which is declared inside the constructor instance of a class but I guess I am doing something logically wrong. For instance consider the following example

I am trying to reuse an opened file which is declared inside the constructor instance of a class but I guess I am doing something logically wrong. For instance consider the following example

class Temp:
    def __init__(self):
        self.open_file_ = open('periodic_status','r')

    def function1(self):
        new_file = self.open_file_
        for i in new_file:
            print 'test1'

    def function2(self):
        for j in self.open_file_:
            print 'test2'

if __name__ == '__main__':
    obj1 = Temp()
    obj1.function1()
    obj1.function2()

In the above program I can print test1 but I am not able to print the statement test2. Can some one ex开发者_Python百科plain me the logic.

Thanks


Because your file handle has exhausted all the lines in the file. You need to rewind it in "function2" using:

f.seek(0)

to start over again

See here docs.python.org


Copying the reference does not create a new iterator; the first round of iteration consumes the entire file, leaving none for the second. You'll need to seek back to the beginning if you want to read it again.


You should add open_file_.seek(0) in the beginning of function to reset the file position to the beginning (its at the end of the file after reading it all in function1()).

0

精彩评论

暂无评论...
验证码 换一张
取 消