title: Given a filename, go to the next file in a directory
body: <p>I am writing a method that takes a filename and a path to a directory and returns the next available filename in the directory or <code>None</code> if there are no files with names that would sort after the file.</p>
  
  <p><a href="https://stackoverflow.com/questions/3964681/find-all-files-in-directory-with-extension-txt-in-python">There are plenty of questions</a> <a href="https://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory">about how to list all the files in a directory</a> <a href="https://stackoverflow.com/questions/10377998/how-can-i-iterate-over-files-in-a-given-directory">or iterate over them</a>, but I am not sure if the best solution to finding a single next filename is to use the list that one of the previous answers generated and then find the location of the current file in the list and choose the next element (or <code>None</code> if we're already on the last one).</p>
  
  <hr>
  
  <p>EDIT: here's my current file-picking code.  It's reused from a different part of the project, where it is used to pick a random image from a potentially nested series of directories.</p>
  
  <pre><code># picks a file from a directory
  # if the file is also a directory, pick a file from the new directory
  # this might choke up if it encounters a directory only containing invalid files
  def pickNestedFile(directory, bad_files):
      file=None
      while file is None or file in bad_files:
          file=random.choice(os.listdir(directory))
      #file=directory+file # use the full path name
      print "Trying "+file
      if os.path.isdir(os.path.join(directory, file))==True:
          print "It's a directory!"
          return pickNestedFile(directory+"/"+file, bad_files)
      else:
          return directory+"/"+file
  </code></pre>
  
  <p>The program I am using this in now is to take a folder of chatlogs, pick a random log, starting position, and length.  These will then be processed into a MOTD-like series of (typically) short log snippets.  What I need the next-file picking ability for is when the length is unusually long or the starting line is at the end of the file, so that it continues at the top of the next file (a.k.a. wrap around midnight).</p>
  
  <p>I am open to the idea of using a different method to choose the file, since the above method does not discreetly give a separate filename and directory and I'd <a href="https://stackoverflow.com/questions/16685384/finding-the-indices-of-matching-elements-in-list-in-python">have to go use a <code>listdir</code> and match to get an index</a> anyway.</p>