一个判断文件扩展名的函数
def fileType(fName): ''' 返回文件扩展名 如x.py则返回py ''' i=0 for c in fName: i+=1 if c=='.': pos=i if pos==len(fName): return 'Error' else: return fName[pos:] print fileType('aa.sf.sdfpy.exe')
测试结果
IDLE 1.2.4 ==== No Subprocess ==== >>> exe >>>
版本二
def fileType(fName): ''' 返回文件扩展名 如x.py则返回py ''' if len(fName)==0: return 'Error' i=0 for c in fName: i+=1 if c=='.': pos=i if pos==len(fName): return 'Error' else: return fName[pos:] print fileType('')
版本三(效率上比上两个要高)
def fType(fname): ''' 返回文件扩展名 如x.py则返回py ''' i=len(fname) while(1): i-=1 if fname[i]=='.':return fname[i+1:] if i==0:return False print fType('./x1/x2/n1.n2.n3.py.txt')
测试结果:
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================ >>> txt >>>