Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question