title: Python: Function to skip comment lines of open file and pass file object with current line
body: <p>I am trying to write some Python code to edit some (existing) input and output files for a particular piece of software. All the files I'm interested in may start with comment line(s) whose first character is # (number of comment lines unknown).</p>
  
  <p>I always want to skip those comment line(s) to read/store important text. Thus, I'd like to create a function that, for a file object that is open in read mode, it will skip the comment lines such that the next call to read from the file object is at the first non-comment line of the file. Currently I am trying to create a class and then use the skip_comments() method (see code below):</p>
  
  <pre><code>import os
  class FileOperations:
  
      def __init__(self, directory, filename):
          self.directory = directory
          self.filename = filename
          self.filepath = os.path.abspath(os.path.join(directory,filename))
          self.fo = open(self.filepath,'r')
  
      def skip_comments(self):
          """ Passes the current position to the location of the first non-comment 
          line of self.fo"""
  
          for line in self.fo:
              if not line.lstrip().startswith('#'):
                  break
          print line ## Just to check if in correct spot
  </code></pre>
  
  <p>Instantiating a class object works and I can do normal object file operations like read() and seek():</p>
  
  <pre><code>In [47]: fh = FileOperations('file_directory','file.txt')`
  In [48]: fh.fo.read(10)
  Out[48]: '#This file'`
  In [49]: fh.fo.seek(0)
  </code></pre>
  
  <p>But when I try to use the skip_comments() method and then read from the object file I have problems:</p>
  
  <pre><code>In [50]: fh.skip_comments()
  20 740 AUX IFACE AUX QFACT AUX CELLGRP
  
  Out[50]: &lt;open file '... file_dir\file.txt', mode 'r' at 0x0000000008797D20&gt;
  In [51]: fh.fo.read(10)
  ---------------------------------------------------------------------------
  ValueError                                Traceback (most recent call last)
  &lt;ipython-input-51-20f04ae797fe&gt; in &lt;module&gt;()
  ----&gt; 1 fh.fo.read(10)
  
  ValueError: Mixing iteration and read methods would lose data 
  </code></pre>
  
  <p>Can someone help me fix this bug or suggest a better way of doing this? Thank you!</p>