1

I have a class which reads a .txt file and performs some various functions to it. I have provided an example of my code below.

class Example(object):
  def __init__(self,fileName):
    self.file = open(fileName)

  def function_a(self):
    for line in self.file:
      for char in line:
        #Do some things

  def function_b(self):
    for line in self.file:
      for char in line:
        #Do some other things

When I create the object and call function_a or function_b everything works perfectly. However, if I call function_b AFTER I call function_a (or vise versa) the first function called works perfect but the second function acts as if self.file is empty.

I can only assume that there is some sort of counter or pointer embedded in self.file that has been activated by my first function and now rests at the end of the file. As a result when I try to call the second function it picks up where the pointer is and after noticing that there are no more lines left, it returns without any errors.

Assuming that I can not combine function_a and function_b to perform both their actions at the same time, how do I reset self.file so that when I try to iterate through it a second time it will start from the beginning?

Or are my assumptions wrong and is something else going on altogether?

Joel Johnson
  • 186
  • 7

2 Answers2

3

After you iterate through a file you'll need to tell it to go back to the beginning.

self.file.seek(0)

Should do what you are looking for.

kevswanberg
  • 2,079
  • 16
  • 21
2

self.file is an iterator, which can be only used once. This means after you iterated in your function_a over it, it's not possible to use it in function_b. I think a good solution would be to store the file in a list i.e.

def __init__(self, fileName):
    with open(fileName, 'r') as f:
        self.file_list = f.readlines()

This should work if the file is not to large otherwise you can also set the filepointer to the beginning of the file with f.seek(0).

jrsm
  • 1,595
  • 2
  • 18
  • 39