提问人:GrayFox 提问时间:8/19/2023 更新时间:8/19/2023 访问量:43
在 while 循环中传递的 if 语句 [duplicate]
if statement passed in a while loop [duplicate]
问:
我最近开始学习编码,并想为 python 制作一个文件排序器,它按文件类型排序,然后按文件创建日期排序。为了控制排序,我想创建一个可以做到这一点的输入(sortByDate = input(“如果要按日期排序,请键入 y:”))。但是由于某种原因,SBD(按日期排序)变量一直作为 True 传递,而不是被归类为 False 并打破循环。
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, "-"))
程序首先创建一些需要的列表和变量,然后要求输入我输入要排序的文件夹路径。之后,程序扫描文件并创建文件类型(键)和这些文件夹(值)的新路径的字典,然后 olso 对文件夹进行编辑。然后它将文件移动到新文件夹,之后是即使 SBD 为 False 也会执行的 if statnet。目标是通过在 sortByDate 变量中键入任何其他内容,它不会更改 SBD 变量,并且程序的最后一步将被跳过。 请康复。
答:
1赞
Danendra
8/19/2023
#1
代码中的问题位于条件中
if sortByDate.lower() == "y" or "yes":
在 while 循环中。条件
sortByDate.lower() == "y"
将正确检查 sortByDate 在转换为小写时是否等于“y”。但是,条件的第二部分或“yes”将始终计算为 True,因为非空字符串在 Python 中被认为是真实的。
尝试将其更改为
if sortByDate.lower() == "y" or sortByDate.lower() == "yes":
评论
2赞
CtrlZ
8/19/2023
或者,如果 {'y', 'yes'} 中的 sortByDate.lower()
评论