python os.walk遍历目录

编程入门 行业动态 更新时间:2024-10-12 22:29:05

python os.walk<a href=https://www.elefans.com/category/jswz/34/1771029.html style=遍历目录"/>

python os.walk遍历目录

目录遍历

包:

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=[]

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()方法操作更加方便,实用。如果你想要顶层目录只需要在第一次迭代后break一下即可.

更多推荐

python os.walk遍历目录

本文发布于:2024-02-12 12:02:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1687711.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   目录   python   os   walk

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!