title: Avoid to write '\n' to the last line of a file in python
body: <p>I'm writing multiple lines to a new file (could be up to several GB), like this:</p>
  
  <pre><code>for item in record:
      output_pass.write('%s\n' %item)
  </code></pre>
  
  <p>However, I got a blank line due to the '\n' of my last record, such as:</p>
  
  <p>Start of the file</p>
  
  <pre><code>record111111
  
  reocrd222222
  
  record333333
  
  ---a blank line---
  </code></pre>
  
  <p>End of a file</p>
  
  <p>Since my file is large, I would not want to read the file again. So, is there an easy way to prevent this, or easy way to remove the last '\n' from the file?</p>
  
  <p>My solution:</p>
  
  <p>Thanks for all the help!</p>
  
  <p>I think I will not load the entire file to the memeory, since it may get very huge.</p>
  
  <p>I actually solve this by first write the first record, then write the rest line in a loop. I put '\n' in the front so it won't appear on the last line.</p>
  
  <p>But Jonathan is right. I actually have now problem with the '\n' in the last line, majorly it is my OCD.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>rec_first = parser_fastq.next() #This is just an iterator of my file
  output.write('%s' %('&gt;'+rec_first[0].strip('@')))
  output.write('\n%s' %(rec_first[1])) #I put '\n' in the front
  
  count = 1
  
  #Write the rest of lines
  for rec_fastq in parser_fastq:
      output.write('\n%s' %('&gt;'+rec_fastq[0].strip('@')))
      output.write('\n%s' %(rec_fastq[1]))
      count += 1
      print 'Extracting %ith record in %s ...' %(count, fastq_name) + '\b'*100,
  
  output.close()
  </code></pre>
  
  <p>print '\n%i records were wrote to %s' % (count, fasta_name)</p>