You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python文件排序工具问题:while循环中if判断错误致SBD始终为True

问题排查与解决

核心问题:条件判断逻辑错误

你的代码中这一行的逻辑存在严重错误:

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

这行代码的实际执行逻辑是 (sortByDate.lower() == "y") or ("yes"),而字符串"yes"在布尔判断中永远会被视为True,因此无论你输入什么内容,这个条件都会成立,导致SBD始终被设为True。

正确的写法需要分别判断两种输入情况:

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

或者更简洁的集合判断写法:

if sortByDate.lower() in {"y", "yes"}:

其他潜在问题修复

  1. 变量初始化位置错误
    当前代码中Files和folderTypes在循环外初始化,若多次输入不同路径处理,这两个变量会累积之前的文件和文件夹信息,导致后续处理出错。需将它们移到while循环内部,每次处理新路径时重置:

    while True :
        Files=[]
        folderTypes={}
        SBD = False
        path = pathlib.Path(input("Enter in the directories path, to stop type stop:"))
        # 后续代码...
    
  2. 错误的break逻辑
    原代码中else: break会在SBD为False时直接跳出整个循环,无法继续处理下一个路径。需删除这个break,让程序完成当前路径的类型排序后,回到循环开头等待下一个输入。

修正后的完整代码

import pathlib
import os, time
import shutil

# files that dont need to be moved
DMFiles = [".ini"]

# Input stage.
while True :
    Files=[]
    folderTypes={}
    SBD = False
    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() in {"y", "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)
                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:
        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!")
print("!DONE!".center(100, "-"))

内容的提问来源于stack exchange,提问作者GrayFox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 08:53:14