Skip to content

Instantly share code, notes, and snippets.

@hcgatewood
Last active July 29, 2016 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hcgatewood/bba7fd58e883a1018b1d to your computer and use it in GitHub Desktop.
Save hcgatewood/bba7fd58e883a1018b1d to your computer and use it in GitHub Desktop.
Sort a list of movies based on a viewed/not-viewed indicator
"""order_movies.py
Sorts a list of movies stored in 'Movies to watch.txt'.
@author Hunter Gatewood
"""
FILE_NAME = 'Movies to watch.txt'
def sort_key(entry):
"""Form a sort key for ordering the movies.
Ignores leading characters of the form '#' and 'the', capitalization
ignored.
"""
if len(entry) >= 4:
if entry[:4].lower() == 'the ':
return entry[4:]
if len(entry) >= 5:
if entry[:5].lower() == '#the ':
return '#' + entry[5:]
return entry
F = open(FILE_NAME, 'r+')
# Open the file and sort the movies into moviesList
MOVIES_STR = F.read()
moviesList = MOVIES_STR.split('\n')
while '' in moviesList:
moviesList.remove('')
moviesList.pop(0)
moviesList = sorted(moviesList, key=sort_key)
# Close the file and then open for writing only (clears the file of text)
F.close()
F = open(FILE_NAME, 'w')
# Write the sorted movies to the file
F.write('Movies to watch\n\n')
for u in moviesList:
F.write(u + '\n')
F.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment