python类库31[文件和目录os+os.path+shutil]


一 常用函数

os模块

os.sep 表示默认的文件路径分隔符,windows为\, linux为/
os.walk(spath): 用来遍历目录下的文件和子目录
os.listdir(dirname):列出dirname下的目录和文件
os.mkdir() : 创建目录
os.makedirs(): 创建目录,包含中间级目录
os.remove():删除文件,不能是目录
os.rmdir():删除空目录
os.removedirs(path):删除目录及其子目录
os.rename(src, dst) :修改文件名
os.renames(old, new) :修改文件或目录名,包含中间级

os.chdir("/tmp") : 更改当前目录
os.chmod( "c:\\test\\buildid.txt", stat.S_IWRITE ) : 去除文件的只读属性

os.path模块

os.path.pathsep 表示默认的路径间的分隔符,windows为; Linux为:
os.path.isdir(name):判断name是不是一个目录,name不是目录就返回false
os.path.isfile(name):判断name是不是一个文件,不存在name也返回false
os.path.exists(name):判断是否存在文件或目录name
os.path.getsize(name):获得文件大小,如果name是目录返回0L
os.path.getctime(name):获得文件的创建时间

os.path.getmtime(name):获得文件的修改时间

os.path.getatime(name):获得文件的最后访问时间

 

os.path.isabs(name):测试是否是绝对路径
os.path.abspath(name):获得绝对路径
os.path.normpath(path):规范path字符串形式

os.path.relpath(path, start='.'):返回路径的相对版本

os.path.split(name):分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在)
os.path.splitext():分离文件名与扩展名
os.path.splitdrive():分离驱动名或unc名字
os.path.join(path,name):连接目录与文件名或目录

os.path.basename(path):返回文件名
os.path.dirname(path):返回文件路径

os.path.expanduser("~"):用来获得user的home路径。


shutil模块
shutil.copyfile(src, dst): 拷贝文件
shutil.copytree(srcDir, dstDir) : 拷贝目录

 

shutil.rmtree('dir') : 删除非空文件夹

shutil.move('old','new') :修改文件和目录名称

 

glob模块

匹配文件:glob.glob(r”c:\linuxany\*.py”)
 

二 实例 (os.walk的遍历过程如下)



import os

# tree c:\test /f
#
C:\TEST
#
│  test.log
#

#
├─test2
#
│      test2.log
#

#
└─test3

tree 
= os.walk('C:/test')
for directoryItem in tree:
    directory
=directoryItem[0]
    subDirectories
=directoryItem[1]
    filesInDirectory
=directoryItem[2]    
    
print('-----------------')
    
print('the directory is :', directory)
    
print('the sub directories are : ', subDirectories)
    
print('the files are :', filesInDirectory)

#-----------------
#
the directory is : C:/test
#
the sub directories are :  ['test2', 'test3']
#
the files are : ['test.log']
#
-----------------
#
the directory is : C:/test\test2
#
the sub directories are :  []
#
the files are : ['test2.log']
#
-----------------
#
the directory is : C:/test\test3
#
the sub directories are :  []
#
the files are : []


完!

 

posted @ 2009-12-16 15:24  iTech  阅读(2260)  评论(0编辑  收藏  举报