title: Sorting contents of a text file alphabetically in Python
body: <p>I would like to alphabetically sort the file inside the variable 'infofile'. My current code to do this does not work, with the file remaining untouched. The program itself is a basic questionnaire, created to experiment reading and writing to files.</p>
  
  <pre><code>import time
  import sys
  
  name = input("What is your first name?").upper()
  
  age = input("How old are you?")
  while not age.isdigit():
      print("Please Only Enter Numbers.")
      age = input("How old are you?")
  
  if int(age) &lt;16:
      infofile = "DatabaseMinor.txt"
  elif int(age) &gt;15 and int(age) &lt;22:
      infofile = "DatabaseYoungAdult.txt"
  elif int(age) &gt;21 and int(age) &lt;65:
      infofile = "DatabaseAdult.txt"
  else:
      infofile = "DatabaseSenior.txt"
  
  gender = input("Are you [M]ale or [F]emale?").upper()
  while gender not in {'M', 'F'}:
      print("Please Only Enter M Or F.")
      gender = str(input("Are you [M]ale or [F]emale?")).upper()
  
  location = input("What country are you from? (UK)").upper()
  while location not in {'ENGLAND', 'SCOTLAND', 'WALES', 'NORTHERN IRELAND'}:
        print("Please Only Enter A Valid Country Within The UK.")
        location = input("What country are you from?").upper()
  
  #Compilation of inputs into a single line format
  userinfo = name + " " + str(age) + " " + gender + " " + location + " " + (time.strftime("%d/%m/%Y")) + " " + (time.strftime("%H:%M:%S")) + '\n'
  
  #Opening and writing value of the userinfo variable to the appropriate text file
  file = open(infofile, 'a')
  file.write(userinfo)
  file.close()
  
  file = open(infofile)
  lines = file.readlines()
  lines.sort()
  file.close()
  </code></pre>
  
  <p>Thanks in advance.</p>