A Python script of escaping characters in linux.

Some times the filenames or directories that contains symbol or space such like ‘[example] {symbol} \simple’, the command may not be execute correctly because the system can not find such a directory or file due to it thought the file or dir is not a complete one but multiple. The we need to escape specific symbols in the filename.

# -*- coding:UTF-8 -*-
def escape(m, n = 0): #define a function
    t = list(m) #convert string to list
    ngword = ['*', '?', '[', ']', '^', '!', '{', '}', '(', ')', '\''] #escape these symbols
    tm = 1
    for i in ngword:
        if n == len(t): 
            break
        elif t[n] == i:
            t.insert(n, "\'\\")
            t.insert(n+2, "\'")
            n += 3
            escape(t,n)
        elif tm < len(ngword):
            tm += 1
            continue
        else:
            n += 1
            escape(t,n)
    return ''.join(t)