How to direct output into file in Python to allow sorting

After being given the solution on how to extract the needed info from a JSON file, I now need to direct that output into a new file. The code for extracting is:

for result in developer['result']:
cases = (result['number'])
print(cases)

I added the print(cases) to validate the right data. So now I have an output that looks like this in my console:

case_1
case_3
case_2
case_4
case_5

I have tried many variations on this theme:

with open("cases.txt", "w") as out_file:
for case in cases:
   out_file.write("{}n".format(case))

Most of the time, the only entry I have in the case is case_5. I thought this was to iterate over the list found in cases and then write them to the file.

I also tried to use a variable for the file:

myFile = open('cases.txt', 'w')
for element in cases:
    myFile.write(element)
    # myFile.write('n')
myFile.close

I will worry about sorting the list once I can get them into a file. Unless someone has a quick and dirty way of sorting the list prior to the file write?

Answer

You are overwriting your cases variable every time. So, the final value that will be stored in cases will be of case_5 i.e. the cases variable will be a tuple containing only case_5. Since you need to write all the cases in the file, I would suggest creating a list of cases and then write that in the file. Following is the implementation:

cases = []
for result in developer['result']:
  cases.append(result['number'])

cases = sorted(cases) # sorting your list assuming that you don't need to sort by any key.

with open("cases.txt", "w") as out_file:
  for case in cases:
    out_file.write("{}n".format(case))