Python_目录操作_os.path.splitext()


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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM