title: Read/Write Loop Text File with Python
body: <p>I want to open an existing txt file and search for line of text appearing many times and in different places. Each time search found, insert 2 new rows below it with specified text.</p>
  
  <p>I tried this code but got 'AttributeError' on 'Path.write' line ('str' object has no attribute 'write').   </p>
  
  <pre><code>Path = '...\\Test.txt'
  searchString = '* Start *'
  
  with open(Path, 'r+') as f:
      content = f.readlines()
  
  nextLine = False 
  
  for line in content:
      if searchString in line:
          nextLine = not nextLine
  else:
      if nextLine:
          Path.write('Name\nDirection')
          nextLine = not nextLine
      else:
          pass
  </code></pre>
  
  <p>I must also allocate to 'Direction' line a number, starting at 0 and increment by 15 until all file is read. So after first instance is found, two lines are inserted into existing txt file like this;</p>
  
  <pre><code>...some text in the existing text file....
  * Start *
  Name
  Direction 0
  </code></pre>
  
  <p>0 then changes to 15 on next instance (ie Direction 15), then 30 (ie Direction 30) etc until end of file.</p>
  
  <p>EDITED CODE: Simplified coded. Anyone vote me up I'd appreciate</p>
  
  <pre><code>Path = '...\\Test.txt'
  
  direction_number = 0
  #Open new file
  Newfile = open(Path, 'w')
  
  #read other file
  with open(Path, 'r') as f:
      content = f.readlines()
  
  #if find special text, write other lines to new file            
  for line in content:
      Newfile.write(line)
      if searchString in line:
          Newfile.write('Name\nDirection %d' % direction_number)
          direction_number += 15
  
  Newfile.close()
  </code></pre>