1. 程式人生 > >Linux 檔名合法性檢測

Linux 檔名合法性檢測

Linux 檔名合法性檢測

Linux 檔名合法性一般規則:

  • 檔名長度不超過255
  • 避免使用加號、減號或者"."作為普通檔案的第一個字元
  • 檔名避免使用下列特殊字元,包括製表符和退格符

Python 示例如下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

def check(filename):
    """
    Linux 檔名合法性檢測
    """
    # 檔名長度不能超過255
    if len(filename) > 255:
        print 'file name invalid'
return # 避免使用加號、減號或者"."作為普通檔案的第一個字元 black_list = ['+', '-', '.'] if filename[0] in black_list: print 'file name invalid' return # 檔名避免使用下列特殊字元,包括製表符和退格符 black_list = ['/', '\t', '\b', '@', '#', '$', '%', '^', '&', '*', '(', ')', '[', ']'] intersection =
set(black_list) & set(filename) if len(intersection) != 0: print 'file name invalid' return print 'file name valid' if __name__ == '__main__': check("test.txt")

直接使用正則表示式:

import re
fileName = "a.txt"
p = "^[^+-./\t\[email protected]#$%*()\[\]][^/\t\[email protected]
#$%*()\[\]]{1,254}$"
if not re.match(p, fileName): print 'file name invalid'