So I'm making a website and in one of the pages you can upload images.
I didn't think of this before when making my file upload function but files are allowed to have multiple .
in them, so how can I differentiate between the "real" .
and the fake .
to get the filename and the extension.
This is my file upload function, which isn't especially relevant but it shows how I upload the files:
def upload_files(files, extensions, path, overwrite=False, rename=None):
if not os.path.exists(path):
os.makedirs(path)
filepath = None
for file in files:
name, ext = file.filename.split('.')
if ext in extensions or extensions == '*':
if rename:
filepath = path + rename + '.' + ext if path else rename + '.' + ext
else:
filepath = path + file.filename if path else file.filename
file.save(filepath, overwrite=overwrite)
else:
raise Exception('[ FILE ISSUE ] - File Extension is not allowed.')
As you can see I am splitting the filename based on the .
that is there but I now need to split it and figure out which .
split pair is the actual pair for filename and extension, it also creates the issue of providing too many values for the declaration name, ext
since there is a third var now at least.
Sounds like you are looking for os.path.splitext
which will split your filename into a name and extension part
import os
print(os.path.splitext("./.././this.file.ext"))
# => ('./.././this.file', '.ext')