title: Write a python program that finds all files with a given prefix and fill the gap
body: <p>I am a beginner of python.  I have this task:</p>
  
  <p>Write a program that finds all files with a given prefix, such as spam001.txt, spam002.txt, and so on, in a single folder and locates any gaps in the numbering (such as if there is a spam001.txt and spam003.txt but no spam002.txt). Have the program rename all the later files to close this gap.</p>
  
  <p>I have written my code, and it seems to work, but it looks ugly, not elegant.  Especially the 3 if statements. How can I shorten it?</p>
  
  <p>Here is my code:</p>
  
  <pre><code># My main idea is to copy the file which is not in right order,
  # and rename it, then delete it.
  
  import os, re, shutil
  
  
  # Arguments: folder, prefix
  def fillGap(folder,prefix):
  
  
      # Create regex with prefix + number + extension.
      fileRegex = re.compile(r'(%s)((\d)(\d)(\d))\.txt' % prefix)
  
      # Makee sure the path is absolute.
      folder = os.path.abspath(folder)
  
      # When I commented the following one line, the program outptu is
      # FileNotFoundError: [Errno 2] No such file or directory:   'spam004.txt'
      os.chdir(folder)  # This line is to avoid the FileNotFoundError.
  
      # Make a list to contain the file with prefix.
      fileNames = list()
      for filename in os.listdir(folder):
          if re.search(fileRegex, filename):
              fileNames.append(filename)
      # Make sure the fileName in the list have a right order.
  
      fileNames.sort()
      print(fileNames)
      # Find the gap through incremting loops
      for i in range(len(fileNames)):
          mo = re.search(fileRegex, fileNames[i])
          if int(mo.group(2)) == i + 1:
              continue
          # The group(2) has three digits, so it need to 3 Ifs.
          # Copy the old file and rename it then delete the old one.
          if i + 1 &lt; 10:
              shutil.copy
              newFileName =prefix + '00' + str(i + 1) + '.txt'
              shutil.copy(fileNames[i], newFileName)
              os.unlink(fileNames[i])
          elif i + 1 &lt; 100:
              shutil.copy(fileNames[i], prefix + '0' + str(i+1) + '.txt')
              os.unlink(fileNames[i])
          else:
              shutil.copy(fileNames[i], prefix + str(i+1) + '.txt')
              os.unlink(fileNames[i])
  
  folder = '/home/jianjun/spam/'
  prefix = 'spam'
  
  fillGap(folder, prefix)
  </code></pre>