Chinaunix首页 | 论坛 | 博客
  • 博客访问: 91203
  • 博文数量: 26
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 291
  • 用 户 组: 普通用户
  • 注册时间: 2014-01-22 16:05
文章分类
文章存档

2014年(26)

分类: Python/Ruby

2014-05-08 20:50:09

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


os.path模块

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


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

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


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

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


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

split()

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

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


os.path.splitext(“文件路径”)    分离文件名与扩展名;默认返回(fname,fextension)元组,可做分片操作
1
2
3
4
5
6
    
>>> 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
1
2
3
4
5
6
    
>>> os.path.exists('/home/addam/aa/test.txt')
True
>>> os.path.exists('/home/addam/')       
True
>>> os.path.exists('/home/addam/test')
False

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


1
2
    
>>> os.path.isabs('/home/addam/')
True

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


1
2
3
4
    
>>> os.path.isfile('/home/addam/aa/test.txt')
True
>>> os.path.isfile('/home/addam/aa')     
False


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


  查询文件信息:


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


1
2
    
>>> os.path.getatime('/home/addam')
1397222714.6862574

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


1
2
    
>>> 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()    返回文件创建时间


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


1
2
    
>>> os.path.getctime('/home/addam')
1397222712.2982574

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

   
1
2
    
>>> time.strftime('%Y_%m_%d %H:%M:%S',time.localtime(os.path.getctime('/home/addam/')))         
'2014_04_11 21:25:12'

   
1
2
    
>>> os.path.getmtime('/home/addam')                                           
1397222712.2982574
阅读(2208) | 评论(0) | 转发(1) |
0

上一篇:声明数组参数

下一篇:python os模块总结

给主人留下些什么吧!~~