I have a simple function that sorts a dictionary:
data = inputfile.readlines()
lineData = sorted(data, key=len, reverse=True)[:3]
Printing the output:
print sorted(data, key=len, reverse=True)[:3]
generates the expected result, however writing to file:
outputfile.writelines sorted(data, key=len, reverse=True)[:3]
generates nothing. How can I write the output to the text file (outputfile)?
The complete code is as follows:
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)
writelinesis a method, you need to call it:ETA
Function
openprovides file handle which could be iterated over once. You do it in yourdo_something_with_inputfunction, after theinputfileiterated over, iterator is exhausted. Which means any further iterations, such as done in yourwrite_resultsfunctions would yield an empty sequence. That’s why nothing is written to the output file. Basically, it is equivalent to:What you need to do is store the output of the
sorted(...)and then write it to the file, not try to generate it again.