Search code examples
pythonif-statementvariableswhile-loop

if statement passed in a while loop


I recently started to learn coding and wanted to make a file sorter for python that sorts by file type and then by file cration date. To controle the sorting I wanted to create a input that makes that posible (sortByDate = input("If you want to sort by date type y:")). But for some reason the SBD (sort by date) variable keeps being passed as True instead off being catagorised as False and breaking the loop.

import pathlib
import os, time
import shutil

Files=[]
folderTypes={}
#files that dont need to be moved
DMFiles = [".ini"]
SBD = False

#Input stage.
while True :
    path = pathlib.Path(input("Enter in the directories path, to stop type stop:"))
    if str(path) == "stop":
        print("Program stoped.")
        break
    elif path.is_dir() == False:
        print("ERROR wrong directory! \n(check spelling or path)")
        continue
    
    sortByDate = input("If you want to sort by date type y:")
    if sortByDate.lower() == "y" or "yes":
        SBD = True
        FolderDateTypes = {}

    #Identifying files and folders, and creating new folders.
    for item in path.iterdir():
        if item.is_file():
            if item.suffix not in DMFiles:
                dir =  path / item.suffix.replace(".", "")
                Files.append(item)
                folderTypes.setdefault(str(item.suffix), dir) if item.suffix not in folderTypes else None
                try:
                    pathlib.Path(dir).mkdir()
                    print(f"New directory created - {dir}")
                except FileExistsError:
                    continue
            else:
                continue
        else:
            continue

    #Moving files to their respective folders.
    print("!Starting to organize files!".center(100, "-"))
    for file in Files:
        newPath = folderTypes.get(file.suffix) / file.name
        shutil.move(file, newPath)
        print(f"{file.name} - succesfuly moved!")
    
    if SBD == True:
        for folder in folderTypes:
            folderFiles = folderTypes.get(folder).iterdir()
            dirDateFolderList = []
            for file in folderFiles:
                fileDateFolder = file.parent / str(time.localtime(os.path.getctime(file)).tm_year)
                if fileDateFolder not in dirDateFolderList:
                    dirDateFolderList.append(fileDateFolder)
                    pathlib.Path(fileDateFolder).mkdir()
                    print(f"New directory created - {fileDateFolder}")
                shutil.move(file, fileDateFolder / file.name)
                print(f"{file.name} - succesfuly moved!")
    else:
        break
print("!DONE!".center(100, "-"))

The program starts off by creating some needed lists and variables, then it asks for inputs where I input the folder path tha is to be sorted. After which is the program scans the files and creates a dictionary of file types (keys) and new paths to those folders (values) and olso crreates the folders. then it moves the files to the new folders, after which comes the if statnet that executes even though SBD is False. The goal is that by typing anything else in the sortByDate variable it dosnt change the SBD variable and the last step of the program gets skiped. PLS healp.


Solution

  • The issue in your code located in the condition

    if sortByDate.lower() == "y" or "yes": 
    

    in the while loop. The condition

    sortByDate.lower() == "y" 
    

    will correctly check if sortByDate is equal to "y" when converted to lowercase. However, the second part of the condition or "yes" will always evaluate to True because non-empty strings are considered truthy in Python.

    Try to change it to

    if sortByDate.lower() == "y" or sortByDate.lower() == "yes":