My program 'technically' works... but there's gotta be a better solution.
So there is a list of top 500 movies in random orders on a text file.
Avatar 71245151
Star Wars 92815125
Matrix 4215151 ......
The question is to create a function that takes the text file as an input and write the top 500 movies in order (Highest to Lowest Sales) to another file.
def sort_films(file_name, destination_file):
open_file = open(file_name, "r") #Read the file
movie_list = []
for line in open_file:
movie_list.append(line.split("\t")) #Since "\t" exists, split
open_file.close()
Here, movie_list would look something like this
movie_list = [['Avatar', '5241521\n'], ['Star Wars', '9512512'], ....]
Since we don't want line breaks when converting the string of numbers into integers and sorting the numbers from high to low, this is what I did. I also put the numbers in the front of each list because sort() sorts the movies in alphabetical order which is not what I want.
for movie in movie_list:
movie.insert(0, movie[1])
movie.pop()
for movie in movie_list:
movie[0] = int(movie[0].replace("\n", ""))
movie_list.sort(reverse = True)
Now I'm going to write the files.
open_file = open(destination_file, "w")
string = ""
I added a line break because we want to display the movie just how it was like in the other text file (after converting the sales into a string.)
Changed the position because the order was [Movie, Sales] initially.
for movie in movie_list:
movie[0] = str(movie[0]) + "\n"
movie.insert(0, movie[1])
movie.pop()
Then we had the "\t" before so I joined the name of the movie and the sales.
string += "\t".join(movie)
open_file.write(string)
open_file.close()
sort_films("top500.txt", "top500result.txt")
I feel like there is a way of sorting the number from high to low without having to change the index (position) in the list...
Would be grateful if anyone can help me out.