title: os.rename deleting files python 3
body: <p>Python novice, my simple script gets a given directory and renames all files sequentially, however it is deleting the files but the print is showing the files names getting renamed, not sure where its going wrong here.</p>
  
  <p>Also, in what order does it retrieve these files?</p>
  
  <pre><code>import os
  
  path = os.path.abspath("D:\Desktop\gp")
  i = 0
  for file_name in os.listdir(path):
  
      try:
          print (file_name + " - " + str(i))
          os.rename(os.path.join(path,file_name), str(i))
      except WindowsError:
          os.remove(str(i))
          os.rename(os.path.join(path,file_name), str(i))
  
      i += 1
  
  print(str(i) + " files.")
  </code></pre>
  
  <p>Edit</p>
  
  <p>Below is the solution with working code, retrieves all files in a dir by creation date and assigns them a iterated number while retaining file extension.</p>
  
  <pre><code>import os
  
  def sorted_dir(folder):
      def getctime(name):
          path = os.path.join(folder, name)
          return os.path.getctime(path)
      return sorted(os.listdir(path), key=getctime)
  
  path = os.path.abspath("D:\Path\Here")
  i = 0
  for file_name in sorted_dir(path):
      _, ext = os.path.splitext(file_name)
      print (file_name + " - " + str(i)+ext)    
      os.rename(os.path.join(path,file_name), os.path.join(path, str(i) + ext))
  i += 1
  
  print(str(i-1) + " files.")
  </code></pre>