Search code examples
pythoncode-cleanup

How can I get rid of these elif statements to write cleaner code? or other clean code suggestions, thank you


nameoffile = input('File name: ')

filename = nameoffile.lower()

if '.gif' in filename:
    print('image/gif')
elif '.jpg' in filename:
    print('image/jpeg')
elif '.jpeg' in filename:
    print('image/jpeg')
elif '.png' in filename:
    print('image/png')
elif '.pdf' in filename:
    print('application/pdf')
elif '.txt' in filename:
    print('text/plain')
elif '.zip' in filename:
    print('application/zip')
else:
    print('application/octet-stream')

Solution

  • Create a dict to map keys to functions or values

    
    
    def check_file_ext(fileName):
      
      file_ext_dict = {
        "zip": "image/gif",
        "png": "image/png",
        ...
      }
      file_type = fileName.split(".")[-1]
      return file_ext_dict[file_type] # might want to try catch incase file extension isn't in your dict