title: How to Skip Folders while looping through a directory?
body: <p>I am writing a program that sorts files in a folder and each time I run the program it sort both files in the target folder and files inside folders in the target folder.</p>
  <p>I want the program to loop through a folder that contains folders and files and skip folders and work on files instead.</p>
  <p>For Clarity:
  Folder A (Root folder) contains:</p>
  <ol>
  <li>files</li>
  <li>folders(B)</li>
  </ol>
  <p><br>I want to loop through A while ignoring all folders(B) in A, I want my program to sort run the rest of the code.</p>
  <p>This is my code:</p>
  <pre><code>import os
  import shutil
  import sys
  
  
  def sortDirectory(directory, func=shutil.copy):
  
      if not os.path.isdir(directory):
          return 1
  
      
      
      for root, dirs, files in os.walk(directory):
  
              
          for file in files:
  
              name, ext = os.path.splitext(file)
              ext = ext[1:]
  
              if not os.path.exists(os.path.join(&quot;out&quot;, ext)):
                  os.makedirs(os.path.join(&quot;out&quot;, ext))
  
              if os.path.exists(os.path.join(&quot;out&quot;, ext, file)):
                  count = 1
                  for newFile in os.listdir(os.path.join(&quot;out&quot;, ext, '')):
                      if name == &quot;_&quot;.join(newFile.split('.')[0].split('_')[:-1]):
                          count += 1
                  outfile = name+'_'+str(count)+'.'+ext
              else:
                  outfile = file
              print('File:', os.path.join(root, file),
                    '-&gt;', os.path.join(&quot;out&quot;, ext, outfile))
              func(os.path.join(root, file), os.path.join(&quot;out&quot;, ext, outfile))
  
      return 0
  
  
  def main():
  
      functionDict = {
          'm': shutil.move,
          'c': shutil.copy,
      }
      flag = shutil.copy
      if len(sys.argv) == 3:
          if sys.argv[2].lower()[0] in functionDict:
              flag = functionDict[sys.argv[2].lower()[0]]
          else:
              print(&quot;Unsupported 3rd argument. Use 'm'ove or 'c'opy&quot;)
              return 1
  
      elif len(sys.argv) == 1 or len(sys.argv) &gt; 3:
          print(
              &quot;Wrong amount of arguments. Only 2 arguments supported: [path function]&quot;)
          return 1
  
      return sortDirectory(sys.argv[1], flag)
  
  
  if __name__ == '__main__':
      main()
  
  </code></pre>