#๐Ÿ”’ is there a way to make this code more efficient?

15 messages ยท Page 1 of 1 (latest)

feral vale
#

here is the code:

file_name = input("file name:  ").lower().strip()
if file_name.endswith((".jpg","jpeg")):
    print("image/jpeg ")
elif file_name.endswith((".png",)):
    print("image/png ")
elif file_name.endswith((".gif")):
    print("image/gif ")
elif file_name.endswith((".pdf")):
    print("application/pdf ")
elif file_name.endswith(("txt")):
    print("text/plain ")
elif file_name.endswith((".zip")):
    print("application/zip ")
else:
    print("application/octet-stream")
grizzled plazaBOT
#

@feral vale

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

blazing dune
#

There is a clear pattern where the folder is simply the name of the extension after the period.

#

The only exceptions is jpg, which you can solve by replacing .jpg with .jpeg before checking which folder it should be placed in.

#

Oh hmm, not exactly just the suffix

#

But you can make a mapping for each suffix to a specific folder name

desert rune
#

I'd use pathlib.Path to do the extension (aka "suffix") detection, then a dictionary to map to your relevant value

blazing dune
#
suffix_to_folder = {
  "jpg": "image/jpeg",
  "png": "image/png",
  etc.
}
#

And pathlib is indeed nicer to get the suffix in a more readable way

feral vale
#

I see

#

I didnt think of that

desert rune
#
from pathlib import Path
fname = input("file name: ")
p = Path(fname.strip())
mapping = {
   ".pdf": "application/pdf",
   ".jpg": "application/jpg",
   ".jpeg": "application/jpg",
   ...
}

result = mapping.get(p.suffix.lower(), "application/octect-stream")

print(result)

something like that maybe

feral vale
#

thank you both very much.

grizzled plazaBOT
#
Python help channel closed using Discord native close action

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.