os.path.splitext(path)
说明:将对应路径的文件名和后缀名分割
示例:
>>> #定义参数内容 ... import os >>> path1='E:\test\6.txt'#文件路径 >>> path2='E:\test'#目录 >>> >>> #用splitext()方法切割 ... split_path1=os.path.splitext(path1) >>> split_path2=os.path.splitext(path2) >>> >>> #打印结果 ... print(split_path1)#正常切割 ('E:\test\x06', '.txt') >>> print(split_path2)#目录切割后异常 ('E:\test', '') >>>
简单运用:统计整个e盘下,txt文件的总数
>>> file_number=0 >>> for root,dirs,files in os.walk("e:\\"): ... for file in files: ... if os.path.splitext(file)[1]==".txt":#将对应的文件与文件名分割 ... file_number+=1 ... #print (file) ... >>> >>> print (file_number) 246
其中os.walk()的简单说明,请参照:python中:os.walk()的简单说明
上面的方法等价于:
>>> for root,dir_name,file_name in os.walk(r"e:"): ... for file in file_name: ... if ".txt" in file: ... count_txt += 1 ... >>> print(count_txt) 246