python os.path.splitext()的用法_python os.path模块

积累一些常用的模块,可以让我们在写程序的时候事半功倍,下面记录一下os.path模块的一些常用函数及用法。

os.path模块

basename('文件路径') 去掉目录路径,返回fname文件名

>>> os.path.basename('/home/addam/aa/test.txt')

'test.txt'

dirname('文件路径') 去掉文件名,返回目录路径

>>> os.path.dirname('/home/addam/aa/test.txt')

'/home/addam/aa'

join()将分离的各部分组合成一个路径名

>>> os.path.join('/addam','test.txt')

'/addam/test.txt'

split()

分割文件名与路径;返回(fpath,fname)元组;如果完全使用目录,它也会将最后一个目录作为文件名分离,且不会判断文件或者目录是否存在

>>> os.path.split('/home/addam/aa/test.txt')

('/home/addam/aa', 'test.txt')

os.path.splitext(“文件路径”) 分离文件名与扩展名;默认返回(fname,fextension)元组,可做分片操作>>> os.path.splitext('/home/addam/aa/test.txt')

('/home/addam/aa/test', '.txt')

>>> os.path.splitext('/home/addam/aa/test.txt')[0]

'/home/addam/aa/test'

>>> os.path.splitext('/home/addam/aa/test.txt')[1]

'.txt'

查询函数:主要是判断真假

exists() 指定路径(文件或者目录)是否存在

>>> os.path.exists('/home/addam/')

True>>> os.path.exists('/home/addam/aa/test.txt')

True

>>> os.path.exists('/home/addam/')

True

>>> os.path.exists('/home/addam/test')

False

isabs() 指定路径是否为绝对路径

>>> os.path.isabs('/home/addam/')

True

isfile() 指定的路径是否为一个文件

>>> os.path.isfile('/home/addam/aa/test.txt')

True

>>> os.path.isfile('/home/addam/aa')

False

samefile() 两个路径名是否指向同一个文件

查询文件信息:

getatime() 返回最近访问时间 (浮点型秒数)

>>> os.path.getatime('/home/addam')

1397222714.6862574

这种时间戳格式的时间看起来太别扭了,怎么办呢?转换一下吧,利用python自带的time模块

>>> time.strftime('%Y_%m_%d %H:%M:%S',time.localtime(os.path.getatime('/home/addam/aa/test.txt')))

'2014_04_11 21:30:30'

getctime() 返回文件创建时间

>>> time.strftime('%Y_%m_%d %H:%M:%S',time.localtime(os.path.getctime('/home/addam/aa/test.txt')))

'2014_04_11 21:25:25

>>> os.path.getctime('/home/addam')

1397222712.2982574

getmtime() 返回最近文件修改时间

>>> time.strftime('%Y_%m_%d %H:%M:%S',time.localtime(os.path.getctime('/home/addam/')))

'2014_04_11 21:25:12'

>>> os.path.getmtime('/home/addam')

1397222712.2982574

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值