55 lines
1.6 KiB
Python
55 lines
1.6 KiB
Python
import os
|
|
import string
|
|
|
|
|
|
def make_valid_filename(input_str):
|
|
if not input_str:
|
|
return input_str
|
|
|
|
# Remove invalid characters
|
|
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
|
|
input_str = input_str.replace("+", " ") # Canvas default for spaces
|
|
input_str = input_str.replace(":", "-")
|
|
input_str = input_str.replace("/", "-")
|
|
input_str = "".join(c for c in input_str if c in valid_chars)
|
|
|
|
# Remove leading and trailing whitespace
|
|
input_str = input_str.lstrip().rstrip()
|
|
|
|
# Remove trailing periods
|
|
input_str = input_str.rstrip(".")
|
|
|
|
return input_str
|
|
|
|
|
|
def make_valid_folder_path(input_str):
|
|
# Remove invalid characters
|
|
valid_chars = "-_.()/ %s%s" % (string.ascii_letters, string.digits)
|
|
input_str = input_str.replace("+", " ") # Canvas default for spaces
|
|
input_str = input_str.replace(":", "-")
|
|
input_str = "".join(c for c in input_str if c in valid_chars)
|
|
|
|
# Remove leading and trailing whitespace, separators
|
|
input_str = input_str.lstrip().rstrip().strip("/").strip("\\")
|
|
|
|
# Remove trailing periods
|
|
input_str = input_str.rstrip(".")
|
|
|
|
# Replace path separators with OS default
|
|
input_str = input_str.replace("/", os.sep)
|
|
|
|
return input_str
|
|
|
|
|
|
def shorten_file_name(string, shorten_by) -> str:
|
|
if not string or shorten_by <= 0:
|
|
return string
|
|
|
|
# Shorten string by specified value + 1 for "-" to indicate incomplete file name (trailing periods not allowed)
|
|
string = string[:len(string) - (shorten_by + 1)]
|
|
|
|
string = string.rstrip().rstrip(".").rstrip("-")
|
|
string += "-"
|
|
|
|
return string
|