rychh

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

 

分类:

技术点:

相关文章:

  • 2021-12-28
  • 2021-06-29
  • 2018-02-03
  • 2021-10-04
  • 2021-11-25
  • 2021-11-25
  • 2021-12-01
猜你喜欢
  • 2021-11-08
  • 2021-10-04
  • 2021-05-27
  • 2021-12-30
  • 2020-10-27
  • 2021-08-09
相关资源
相似解决方案