'For loop doesnt execute for all instances - OS Module Python

The code below reads the first 4 letters of a filename, and if a folder with those 4 letters exists then it shifts that file to that folder. Otherwise, it creates a new folder with the first 4 letters and then moves the file to that new folder.

The problem is that it only reads the name of the first file and creates a folder with its first 4 letters when it is executed and doesn't loop through the rest of the files.

# Loop through files, 
# read first 4 letters of file name, 
# create a folder using the first 4 letters of the file if it doesnt already exsist,
#  If it exsists change directory of the current file to the folder 
#  If it doesnt exsist create a folder with first 4 letters of the file and then set path of that file to that folder. 

import os
import sys
import shutil


# dir="D:\ALPastPapers\All Past Papers - Copy"
dir="D:\ForFileName"

for filename in os.listdir(dir):
    path = dir + "\\" + filename[0:4]
    # double backslash represents single backslash
    if os.path.isfile(path):
        # if folder exsists:
        source= dir + "\\" + filename
        #getting the directory of the current file
        destination= dir + "\\" + filename[0:4]
        # the folder where we move the file
        shutil.move(source, destination)
        # move the file to the folder
    else: 
        os.mkdir(path)
        # make new file
        source= dir + "\\" + filename
        destination= path
        shutil.move(source, destination)

        

    


Solution 1:[1]

It is important to understand the distinction Python sets between files and folders. Files can be recognised by the os.path.isfile() command but since folders are actually considered as directories you would have to use the os.path.isdir() command.

This is why in the code I posted above, specifically this line:

if os.path.isfile(path):

Actually says, " No the path defined is actually a folder and not a file," so the loop quits.

Instead changing that part to

if os.path.isdir(path):

Gives the perfect result.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nimantha