一入python深似海--目录遍历

目录遍历

包:

os  os.path

函数:

os.listdir(dirname):列出dirname下的目录和文件

os.getcwd():获得当前工作目录

os.curdir:返回当前目录('.')

os.chdir(dirname):改变工作目录到dirname

os.path.isdir(name):判断name是不是一个目录,name不是目录就返回false

os.path.isfile(name):判断name是不是一个文件,不存在name也返回false

os.path.exists(name):判断是否存在文件或目录name

os.path.getsize(name):获得文件大小,如果name是目录返回0

os.path.abspath(name):获得绝对路径

os.path.normpath(path):规范path字符串形式

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

os.path.splitext():分离文件名与扩展名

os.path.join(path,name):连接目录与文件名或目录

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

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

递归法

#coding:utf8
import os
def dirList(path,allfile):
    filelist=os.listdir(path)
    for filename in filelist:
        filepath=os.path.join(path,filename)
        if os.path.isdir(filepath):
            dirList(filepath,allfile)
        allfile.append(filepath)


allfile=[]
dirList('D:\\pythonPro\\test',allfile)
print allfile

os.walk()法

os.walk(path)返回一个生成器,可以用next()方法,或者for循环访问该生成器的每一个元素。 他的每个部分都是一个三元组,('目录x',[目录x下的目录list],[目录x下面的文件list])

path='D:\\pythonPro\\test'
allfile1=[]
g=os.walk(path)
for root,dirs,files in os.walk(path):
    for filename in files:
        allfile1.append(os.path.join(root,filename))
    for dirname in dirs:
        allfile1.append(os.path.join(root,dirname))
print allfile1

os.walk()方法操作更加方便,实用。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值