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

Time:12-22

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.

CodePudding user response:

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')

CodePudding user response:

So after going through your query I thought of something which might help you.

Method-1: If you have some pre defined extensions like jpg, png, jpeg, pdf, docx, ppt, csv, xlxd ..... you can make a list of these and use that to separate your file extension

filename = Anindya.Patro.pdf
    
for I in filename.split('.'):
    if I in list_of_files:
      Do your operation

This is a brute force kinda idea.

Method-2: The extensions are always at the last of file name - like you don't find files like Anindya.pdf.Patro So you can access it in two ways

1. By splitting at last . only
2. split the filename and do filename[-1] which will give you the last word after split 
l = filename.split('.')
extension = l[-1]
  • Related