D
D
danyaxaxaxaxa2021-08-07 21:29:44
Python
danyaxaxaxaxa, 2021-08-07 21:29:44

How to optimize elifs?

How to optimize this code?

if Path(file).is_dir():
                new_path = folder_track + '/Folders/' + filename
                os.rename(file, new_path)
            elif Path(file).suffix in audio_extensions:
                new_path = folder_track + '/Audio/' + filename
                os.rename(file, new_path)
            elif Path(file).suffix in photo_extensions:
                new_path = folder_track + '/Photos/' + filename
                os.rename(file, new_path)
            elif Path(file).suffix in archive_extensions:
                new_path = folder_track + '/Archives/' + filename
                os.rename(file, new_path)
            elif Path(file).suffix in application_extensions:
                new_path = folder_track + '/Applications/' + filename
                os.rename(file, new_path)
            elif Path(file).suffix in video_extensions:
                new_path = folder_track + '/Videos/' + filename
                os.rename(file, new_path)
            else:
                new_path = folder_track + '/Other/' + filename
                os.rename(file, new_path)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2021-08-07
@danyaxaxaxaxa

The most banal thing that can be done is to take out the same functions as ifs, namely
os.rename(file, new_path)
, in general -

suffixes = {'Audio': ['.mp3', '.wav'], 'Photos': ['.jpg', '.png'], etc, etc}

suffix = Path(file).suffix

for folder_name, extensions in suffixes.items():
    if suffix in extensions:
        new_path = f'{folder_track}/{folder_name}/{filename}'
        break
else:
    new_path = f'{folder_track}/Other/{filename}'

os.rename(file, new_path)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question