1> os.getcwd()--->得到当前的工作目录
2> os.path.dirname(pathname)
#返回目录名,不包含文件名。注意,不包含目录最后的斜杠
dirname(pathname)=split(pathname)[0]
dirname('/home/test/mytest.py')=>'/home/test'
diname('/home/test/')=>'/home/test'
3>os.path.split(pathname)
#将pathname分割成(路径,文件名)
split('/home/test/mytest.py')=>('/home/test','mytest.py')
split('/home/test/')=>('/home/test','')
4>os.path.join(path1[,path2[,...]])
#合并多个路径
join('/home','test','mytest.py')=>'/home/test/mytest.py'
5>os.path.normpath(pathname)
#将路径规范化,去掉多余的分隔符,将.和..变为真实的路径,处理错误的斜杠
normpath('\home/test')=>'\\home/test'
normpath('/home/./test')=>'/home/test'
normpath('/home/../test')=>'/test'
6>os.path.exists(pathname)
#文件或者路径是否存在并且有权限访问
7>os.path.abs(pathname)
#是否是绝对路径
8>os.path.isfile(pathname)
#是否文件
9>os.path.isdir(pathname)
#是否是目录
10>os.path.islink(pathname)
#是否是链接
11>os.chdir(path)
#改变当前的工作目录
12>os.remove(path)
#删除文件
13>os.system('command')
#等于在命令行输入command
#如输入os.system('ping www.baidu.com')
14>os.walk(path)
#os.walk会遍历path路径
#假如有如下目录结构:
#./aa.txt
#./bb.txt
#./old/cc.txt
#./old/dd.txt
#./old/test1/test1.txt
#./old/test2/test2.txt
#此时有如下代码:
for root,dirs,files in os.walk(path)
print 'root',root
for eachdir in dirs:
print 'eachdir',eachdir
for eachfile in files:
print 'eachfile',eachfile
运行python test.py ./old/
出现如下结果:
root old
eachdir test1
eachdir test2
eachfile cc.txt
eachfile dd.txt
root old/test1
eachfile test1.txt
root old/test2
eachfile test2.txt
python之os类库
最新推荐文章于 2025-01-04 21:34:19 发布