title: python write text to file slower than printing text to terminal with python?
body: <p>I'm writing a program that takes a string and compute all possible repeated permutations from this string. I'll show some fragments of my code, I would be grateful if someone can point me how to improved the speed when sending the data to a file.</p>
  
  <h1>Scenario 1</h1>
  
  <p>Sending the output to stdout took about 12 seconds to write 531,441 lines (3mb)</p>
  
  <pre><code>import itertools 
  for word in itertools.product(abcdefghi,repeat = 6):
      print(word)
  </code></pre>
  
  <h1>Scenario 2</h1>
  
  <p>Then I tried sending the output to a file instead of stdout, and this took a roughly around 5 minutes.</p>
  
  <pre><code>import itertools
  word_counter=0
  for word in itertools.product(abcdefghi,repeat = 6): 
      word_counter=word_counter+1
      if word_counter==1:
          open('myfile', 'w').write(word)
      else:
          open('myfile', 'a').write(word)
  </code></pre>
  
  <p><code>word_counter</code> keep track of the number of repeated permutations as the function is looping. When <code>word_counter</code> is 1 the program creates the file and afterwards append the data to the file when word_counter is greater than 1.</p>
  
  <p>I use a program on the web to do this and I found the program took the same time when printing the data to a terminal and this same web prgoram  took about 3 seconds to output these combinations to a file while my program took 5 minutes to output the data to a file!</p>
  
  <p>I also tried running my program and redirecting output to a file in a bash terminal, and this took the same time (3 sec)!</p>
  
  <pre><code>'myprog' &gt; 'output file'
  </code></pre>