-1

I am working on a Flask blog application, and I am trying to separate a file extension from a filename. For example, for the filename "IMG_0503.jpg," I would like to get "IMG_0503" and ".jpg" separately. I tried the pathlib module and the os.path.splitext() method, but both return an empty file extension instead of ".jpg"

Here is my code with os.path.splitext():

uploaded_file = request.files['file']
print("UPLOADED_FILE:", uploaded_file)
filename = secure_filename(uploaded_file.filename)
print("FILENAME:", filename)

filename = os.path.splitext(filename)[0]
file_ext = os.path.splitext(filename)[1]
print("OS.PATH.SPLITEXT:", os.path.splitext(filename))
print("FILE_EXT:", file_ext)

This is the output of print statements:

UPLOADED_FILE: <FileStorage: 'IMG_0503.jpg' ('image/jpeg')>
FILENAME: IMG_0503.jpg
OS.PATH.SPLITEXT: ('IMG_0503', '')
FILE_EXT:

With the pathlib, the output is exactly the same, but I am using file_ext = pathlib.Path(filename).suffix to get the extension.

Can someone please help me to resolve this issue?

davidism
  • 121,510
  • 29
  • 395
  • 339
Anna
  • 1

1 Answers1

0

Alternate solution:

import pathlib


# function to return the file extension
file_extension = pathlib.Path('my_file.txt').suffix
print("File Extension: ", file_extension)

Output:

File Extension: .txt

jimBeaux27
  • 117
  • 7
  • Thanks! I also figured out that os.path.splitext() was not working because I assigned the return value of os.path.splitext(filename)[0] to the variable called filename. – Anna Dec 30 '21 at 19:11