试图创建一个文件管理器。但所有文件都移动到同一文件夹

时间:2018-02-02 13:57:43

标签: python python-3.x

这是我写的代码。 但每次所有文件都移动到'images'文件夹。 即使在调试器中,变量都显示真值,但文件不会根据条件

移动
from os import mkdir,path,chdir,listdir
from shutil import move
filedirectory = '/root/Downloads'
chdir(filedirectory)
types = ['images','pdf','windows executables','linux tools','other scripts']
for type in types:
        if not path.exists(type):
        mkdir(type)
        files=listdir()
        for file in files:
            if path.isfile(file):
                lists = []
                lists = file.split('.')
                extension = lists[-1]
                if extension == 'jpg' or 'jpeg' or 'png':
                    move(file,'images')
                elif extension == 'exe':
                    move(file,'windows executables')
                elif extension == 'xz' or 'gz':
                    move(file,'linux tools')
                elif extension == 'py' or 'rb':
                    move(file,'other sripts')
                elif extension == 'pdf':
                    move(file,'pdf')

1 个答案:

答案 0 :(得分:2)

关键是,你误解了or是什么以及它在这一行做了什么:

if extension == 'jpg' or 'jpeg' or 'png':

or加入布尔表达式时,第二个和第三个“表达式”(它们是两个评估为True的普通非空字符串)构成整个{{ 1}}语句始终评估为if,因此您的所有文件都会转移到True

实现这一目标的正确方法是:

images

同样适用于。

下的其他行

作为旁注,你可能想要

if extension in ['jpg', 'jpeg', 'png']:

因为各种程序和设备(如相机)生成大写名称的文件。