Read from file, Sort list by revenue, Write to file
I'm given a text file of 500 films formatted as such: "name" \t "gross revenue"
I've to write a function that sorts the films by gross revenue, then write the sorted content to the destination file.
I'm stuck on multiple counts and the error message that appeared is this:
split[1]= int(split[1]) IndexError: list index out of range Command exited with non-zero status 1
import re
def sort_films(source, destination):
source= open(source)
destination = open(destination, "w")
full_list=[]
for line in source:
split= re.split("\t|\n", line)
split.pop()
split[1]= int(split[1])
full_list.append(split)
full_list.sort(key= lambda i:i[1], reverse=True)
print(full_list, file=destination)
source.close()
destination.close()
sort_films("top500.txt", "top500result.txt")
print("Done!")
You are removing the first element of a 2-element list, and then trying to access the second element of a now 1 element list. Either remove split.pop()
or replace the index in split[1] = int(split[1])
with a 0
.