0

this is the code i have written. but everytime all files are moving to 'images' folder. even in debugger,variables are all showing true values,but files are not moving according to if conditions

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')
iBug
  • 35,554
  • 7
  • 89
  • 134
ashwin
  • 17
  • 5

1 Answers1

2

The point is, you're misunderstanding what or is and what it does at this line:

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

As or joins boolean expressions, the 2nd and 3rd "expression", which are two plain non-empty strings that evaluate to True, make the whole if statement always evaluate to True, so all your files are getting moved into images.

The correct way to achieve this is:

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

The same for other lines under.

As a side note, you probably want

extension = lists[-1].lower()

as various programs and devices (like a camera) generate files with uppercase names.

iBug
  • 35,554
  • 7
  • 89
  • 134
  • thanks. it worked. but plz clarify why didn't it worked before? – ashwin Feb 02 '18 at 14:20
  • @rexon `extension == 'jpg' or 'jpeg' or 'png'` is interpreted as `(extension == 'jpg') or ('jpeg') or ('png')`. When string is evaluated into a boolean value, an empty one turns to `False` and a non-empty one turns to `True`. So your previous wrong code is always `True`. – iBug Feb 02 '18 at 14:30