Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if a filename has multiple '.'/periods in it

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading