Python clean filename

18 Python code examples are found related to " clean filename". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: ryfiles.py    From pyradi with MIT License 12 votes vote down vote up
def cleanFilename(sourcestring,  removestring =" %:/,.\\[]<>*?"):
    """Clean a string by removing selected characters.

    Creates a legal and 'clean' source string from a string by removing some 
    clutter and  characters not allowed in filenames.
    A default set is given but the user can override the default string.

    Args:
        | sourcestring (string): the string to be cleaned.
        | removestring (string): remove all these characters from the string (optional).

    Returns:
        | (string): A cleaned-up string.

    Raises:
        | No exception is raised.
    """
    #remove the undesireable characters
    return ''.join([c for c in sourcestring if c not in removestring])



################################################################ 
Example 2
Source File: Content.py    From DownloaderForReddit with GNU General Public License v3.0 8 votes vote down vote up
def clean_filename(name):
        """Ensures each file name does not contain forbidden characters and is within the character limit"""
        # For some reason the file system (Windows at least) is having trouble saving files that are over 180ish
        # characters.  I'm not sure why this is, as the file name limit should be around 240. But either way, this
        # method has been adapted to work with the results that I am consistently getting.
        forbidden_chars = '"*\\/\'.|?:<>'
        filename = ''.join([x if x not in forbidden_chars else '#' for x in name])
        if len(filename) >= 176:
            filename = filename[:170] + '...'
        return filename 
Example 3
Source File: download.py    From cn-mooc-dl with MIT License 6 votes vote down vote up
def clean_filename(string: str) -> str:
    """
    Sanitize a string to be used as a filename.

    If minimal_change is set to true, then we only strip the bare minimum of
    characters that are problematic for filesystems (namely, ':', '/' and '\x00', '\n').
    """
    string = unescape(string)
    string = unquote(string)
    string = re.sub(r'<(?P<tag>.+?)>(?P<in>.+?)<(/(?P=tag))>', "\g<in>", string)

    string = string.replace(':', '_').replace('/', '_').replace('\x00', '_')

    string = re.sub('[\n\\\*><?\"|\t]', '', string)
    string = string.strip()

    return string 
Example 4
Source File: views.py    From protwis with Apache License 2.0 6 votes vote down vote up
def clean_filename(filename, replace=' '):
    char_limit = 255

    # replace spaces
    filename.replace(' ','_')

    # keep only valid ascii chars
    cleaned_filename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore').decode()

    # keep only whitelisted chars
    whitelist = "-_.() %s%s" % (string.ascii_letters, string.digits)
    cleaned_filename = ''.join(c for c in cleaned_filename if c in whitelist)
    if len(cleaned_filename)>char_limit:
        print("Warning, filename truncated because it was over {}. Filenames may no longer be unique".format(char_limit))
    return cleaned_filename[:char_limit] 
Example 5
Source File: Flask_PasteSubmit.py    From AIL-framework with GNU Affero General Public License v3.0 5 votes vote down vote up
def clean_filename(filename, whitelist=valid_filename_chars, replace=' '):
    # replace characters
    for r in replace:
        filename = filename.replace(r,'_')

    # keep only valid ascii chars
    cleaned_filename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore').decode()

    # keep only whitelisted chars
    return ''.join(c for c in cleaned_filename if c in whitelist) 
Example 6
Source File: dalton.py    From dalton with Apache License 2.0 5 votes vote down vote up
def clean_filename(filename):
    return re.sub(r"[^a-zA-Z0-9\_\-\.]", "_", filename)

# handle duplicate filenames (e.g. same pcap sumbitted more than once)
#  by renaming pcaps with same name 
Example 7
Source File: showjar.py    From TTDeDroid with Apache License 2.0 5 votes vote down vote up
def clean_filename(cache, path):
    name = os.path.basename(path)
    pattern = re.compile(u"[-\.\(\)\w]+")
    name2 = '_'.join(re.findall(pattern, name))
    if name != name2:
        newname = "ttdedroid_%s"%(name2)
        newpath = os.path.join(cache, newname)
        shutil.copyfile(path, newpath)
        return newpath
    return path 
Example 8
Source File: Nsp.py    From NSC_BUILDER with MIT License 5 votes vote down vote up
def cleanFilename(self, s):
		if s is None:
			return ''
		#s = re.sub('\s+\Demo\s*', ' ', s, re.I)
		s = re.sub('\s*\[DLC\]\s*', '', s, re.I)
		s = re.sub(r'[\/\\\:\*\?\"\<\>\|\.\s™©®()\~]+', ' ', s)
		return s.strip() 
Example 9
Source File: slurm.py    From sciluigi with MIT License 5 votes vote down vote up
def clean_filename(self, filename):
        '''
        Clean up a string to make it suitable for use as file name.
        '''
        return re.sub('[^A-Za-z0-9\_\ ]', '_', str(filename)).replace(' ', '_')

    #def get_task_config(self, name):
    #    return luigi.configuration.get_config().get(self.task_family, name) 
Example 10
Source File: fileUtils.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def cleanFilename(s):
    if not s:
        return ''
    badchars = '\\/:*?\"<>|'
    for c in badchars:
        s = s.replace(c, '')
    return s; 
Example 11
Source File: codefile.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def clean_filename_type(self):
            filename_type = self.data['filename_type']
            filename = self.data['filename']
            if filename_type == 'REX':
                try:
                    re.compile(filename)
                except re.error as e:
                    msg = str(e)
                    raise forms.ValidationError('Given filename is not a valid regular expression. Error: "%s".' % (msg))
            return filename_type 
Example 12
Source File: download_youtube.py    From crnn-lid with GNU General Public License v3.0 5 votes vote down vote up
def clean_filename(filename):
    valid_chars = "-_%s%s" % (string.ascii_letters, string.digits)
    new_name = "".join(c for c in filename if c in valid_chars)
    new_name = new_name.replace(' ','_')
    return new_name 
Example 13
Source File: utils.py    From xd with MIT License 5 votes vote down vote up
def clean_filename(fn):
    badchars = """ "'\\"""

    basefn = parse_pathname(fn).base
    for ch in badchars:
        basefn = basefn.replace(ch, '_')

    return basefn


# newext always includes the '.' so it can be removed entirely with newext="" 
Example 14
Source File: launcher_plugin.py    From advanced-launcher with GNU General Public License v2.0 5 votes vote down vote up
def clean_filename(title):
    title = re.sub('\[.*?\]', '', title)
    title = re.sub('\(.*?\)', '', title)
    title = re.sub('\{.*?\}', '', title)
    title = title.replace('_',' ')
    title = title.replace('-',' ')
    title = title.replace(':',' ')
    title = title.replace('.',' ')
    title = title.rstrip()
    return title 
Example 15
Source File: osutils.py    From p2ptv-pi with MIT License 5 votes vote down vote up
def last_minute_filename_clean(name):
    s = name.strip()
    if sys.platform == 'win32' and s.endswith('..'):
        s = s[:-2]
    return s 
Example 16
Source File: generic.py    From DeTTECT with GNU General Public License v3.0 5 votes vote down vote up
def clean_filename(filename):
    """
    Remove invalid characters from filename and maximize it to 200 characters
    :param filename: Input filename
    :return: sanitized filename
    """
    return filename.replace('/', '').replace('\\', '').replace(':', '')[:200] 
Example 17
Source File: attack_controller.py    From Raid-Toolbox with GNU General Public License v2.0 5 votes vote down vote up
def clean_filename(filename, whitelist=valid_filename_chars, replace=' '):
        for r in replace:
            filename = filename.replace(r,'_')
        cleaned_filename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore').decode()
        cleaned_filename = ''.join(c for c in cleaned_filename if c in whitelist)
        return cleaned_filename[:char_limit] 
Example 18
Source File: forms.py    From conf_site with MIT License 5 votes vote down vote up
def clean_filename(self):
        if "submit" in self.data:
            fname = self.cleaned_data.get("filename")
            if not fname or not fname.name.endswith(".csv"):
                raise forms.ValidationError("Please upload a .csv file")
            return fname