python中os和os.path模块

python中os.path模块用法

其它函数:

os.path.isabs() 指定路径是否为绝对路径
os.path.isdir() 指定路径是否存在且为一个目录
os.path.isfile() 指定路径是否存在且为一个文件
os.path.islink() 指定路径是否存在且为一个符号链接
os.path.ismount() 指定路径是否存在且为一个挂载点 ???
os.path.samefile() 两个路径名是否指向同一个文件

文件信息:

import os
import time
os.path.getsize(file) #输出文件大小(字节为单位)
os.path.getatime(file) #输出最近访问时间1318921018.0 ( 浮点型秒数)
os.path.getctime(file) #输出文件创建时间
os.path.getmtime(file) #输出最近修改时间
time.gmtime(os.path.getmtime(file)) #以struct_time形式输出最近修改时间
os.path.abspath(file) #输出绝对路径’/Volumes/Leopard/Users/Caroline/Desktop/1.mp4′
os.path.normpath(file) #输出’/Volumes/Leopard/Users/Caroline/Desktop/1.mp4′

一些实际的用法:

获取扩展名:

>>> os.path.splitext('/Volumes/Leopard/Users/Caroline/Desktop/1.mp4')[1:]
('.mp4',)
>>> os.path.splitext('/Volumes/Leopard/Users/Caroline/Desktop/1.mp4')[1]
'.mp4'

判断目录或文件的存在:

>>> os.path.exists('/root/1.py')
True
>>> os.path.exists('/root/')
True
>>> os.path.exists('/root')
True
>>> os.path.isdir('/root')
True

改变工作目录:

>>> os.chdir('/home')
>>> os.getcwd()
'/home'

字符串分割:

>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']

获取文件夹大小:

import os  
from os.path import join, getsize 
def getdirsize(dir): 
   size = 0L 
   for root, dirs, files in os.walk(dir): 
      size += sum([getsize(join(root, name)) for name in files]) 
   return size
if '__name__' == '__main__': 
   filesize = getdirsize(r'c:windows') 
   print 'There are %.3f' % (size/1024/1024), 'Mbytes in c:\windows'
相关的文章:

暂无评论

写评论