Python模块: 文件和目录os+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的遍历过程如下)

 1 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
 2 
 3 import os
 4 
 5 # tree c:	est /f
 6 #C:TEST
 7 #│  test.log
 8 #
 9 #├─test2
10 #│      test2.log
11 #
12 #└─test3
13 
14 tree = os.walk('C:/test')
15 for directoryItem in tree:
16     directory=directoryItem[0]
17     subDirectories=directoryItem[1]
18     filesInDirectory=directoryItem[2]    
19     print('-----------------')
20     print('the directory is :', directory)
21     print('the sub directories are : ', subDirectories)
22     print('the files are :', filesInDirectory)
23 
24 #-----------------
25 #the directory is : C:/test
26 #the sub directories are :  ['test2', 'test3']
27 #the files are : ['test.log']
28 #-----------------
29 #the directory is : C:/test	est2
30 #the sub directories are :  []
31 #the files are : ['test2.log']
32 #-----------------
33 #the directory is : C:/test	est3
34 #the sub directories are :  []
35 #the files are : []

转:http://www.cnblogs.com/itech/archive/2009/12/16/1625636.html

原文地址:https://www.cnblogs.com/WayneZeng/p/9290744.html