title: Python write function output to file
body: <p>I'm sorry if this is silly question but I have no much Python experience</p>
  
  <p>I have function for comparing files</p>
  
  <pre><code>def compare_files(file1, file2):
      fname1 = file1
      fname2 = file2
  
      # Open file for reading in text mode (default mode)
      f1 = open(fname1)
      f2 = open(fname2)
      # Print confirmation
      #print("-----------------------------------")
      #print("Comparing files ", " &gt; " + fname1, " &lt; " +fname2, sep='\n')
      #print("-----------------------------------")
  
      # Read the first line from the files
      f1_line = f1.readline()
      f2_line = f2.readline()
  
      # Initialize counter for line number
      line_no = 1
  
      # Loop if either file1 or file2 has not reached EOF
  
      while f1_line != '' or f2_line != '':
  
         # Strip the leading whitespaces
        f1_line = f1_line.rstrip()
        f2_line = f2_line.rstrip()
  
        # Compare the lines from both file
        if f1_line != f2_line:
  
           ########## If a line does not exist on file2 then mark the output with + sign
          if f2_line == '' and f1_line != '':
              print ("Line added:Line-%d" % line_no + "-"+ f1_line)
           #otherwise output the line on file1 and mark it with &gt; sign
          elif f1_line != '':
              print ("Line changed:Line-%d" % line_no + "-"+ f1_line)
  
  
          ########### If a line does not exist on file1 then mark the output with + sign
          if f1_line == '' and f2_line != '':
              print ("Line removed:Line-%d" % line_no + "-"+ f1_line)
            # otherwise output the line on file2 and mark it with &lt; sign
           #elif f2_line != '':
              #print("&lt;", "Line-%d" %  line_no, f2_line)
  
           # Print a blank line
           #print()
  
      #Read the next line from the file
        f1_line = f1.readline()
        f2_line = f2.readline()
        #Increment line counter
        line_no += 1
  
      # Close the files
      f1.close()
      f2.close()
  </code></pre>
  
  <p>I want to print function output to a text file</p>
  
  <pre><code>result=compare_files("1.txt", "2.txt")
  
  print (result)
  Line changed:Line-1-aaaaa
  Line added:Line-2-sss
  None
  </code></pre>
  
  <p>i tried following:</p>
  
  <pre><code>f = open('changes.txt', 'w')
  
  f.write(str(result))
  
  f.close
  </code></pre>
  
  <p>but only None is printed to changes.txt</p>
  
  <p>I'm using "workaround" sys.stdout but wonder is there any other way instead of redirecting print output.</p>
  
  <p>If in function output I specify return instead of print then I'm getting only first output line (Line changed:Line-1-aaaaa) to changes.txt </p>