write sorted results to file
<p>I have a simple function that sorts a dictionary:</p>

<pre><code>data = inputfile.readlines()
lineData = sorted(data, key=len, reverse=True)[:3]
</code></pre>

<p>Printing the output:</p>

<pre><code>print sorted(data, key=len, reverse=True)[:3]
</code></pre>

<p>generates the expected result, however writing to file:</p>

<pre><code>outputfile.writelines sorted(data, key=len, reverse=True)[:3]
</code></pre>

<p>generates nothing. How can I write the output to the text file (outputfile)?
The complete code is as follows:</p>

<pre><code>import sys, string
inputfilenames, outputfilename = sys.argv[1:-1], sys.argv[-1]


def do_something_with_input(inputfile):
    data = inputfile.readlines()
    print sorted(data, key=len, reverse=True)[:3]
    print sys.path[0]+"/"+ outputfilename


def write_results(outputfile):
    data = inputfile.readlines()
    outputfile.writelines(sorted(data, key=len, reverse=True)[:3])

for inputfilename in inputfilenames:
    inputfile = open(inputfilename, "r")
    do_something_with_input(inputfile)
    outputfile = open(outputfilename, "w")
    write_results(outputfile)
</code></pre>
