Python os.walk文件遍历

os.walk(top, topdown=True, onerror=None, followlinks=False)

可以得到一个三元tupple(dirpath, dirnames, filenames),

第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件。

dirpath 是一个string,代表目录的路径,

dirnames 是一个list,包含了dirpath下所有子目录的名字。

filenames 是一个list,包含了非目录文件的名字。

这些名字不包含路径信息,如果需要得到全路径,需要使用os.path.join(dirpath, name).

通过for循环自动完成递归枚举

a

import os

for i in os.walk(‘c:‘+os.sep+‘ant‘):
    print i

输出:

(‘c:\\ant‘, [‘bin‘, ‘docs‘, ‘etc‘, ‘lib‘, ‘Project‘], [‘fetch.xml‘, ‘get-m2.xml‘, ‘INSTALL‘, ‘KEYS‘, ‘LICENSE‘, ‘NOTICE‘, ‘README‘, ‘WHATSNEW‘])
(‘c:\\ant\\bin‘, [], [‘ant‘, ‘ant.bat‘, ‘ant.cmd‘, ‘antenv.cmd‘, ‘antRun‘, ‘antRun.bat‘, ‘antRun.pl‘, ‘complete-ant-cmd.pl‘, ‘envset.cmd‘, ‘lcp.bat‘, ‘runant.pl‘, ‘runant.py‘, ‘runrc.cmd‘])
(‘c:\\ant\\docs‘, [‘ant2‘, ‘antlibs‘, ‘images‘, ‘manual‘, ‘projects‘, ‘slides‘, ‘webtest‘], [‘antnews.html‘, ‘ant_in_anger.html‘, ‘ant_task_guidelines.html‘, ‘appendix_e.pdf‘, ‘breadcrumbs.js‘, ‘bugs.html‘, ‘bylaws.html‘, ‘contributors.html‘, ‘external.html‘, ‘faq.html‘, ‘favicon.ico‘, ‘index.html‘, ‘legal.html‘, ‘LICENSE‘, ‘license.html‘, ‘mail.html‘, ‘mission.html‘, ‘nightlies.html‘, ‘page.css‘, ‘problems.html‘, ‘projects.html‘, ‘resources.html‘, ‘svn.html‘])
(‘c:\\ant\\docs\\ant2‘, [], [‘actionlist.html‘, ‘features.html‘, ‘FunctionalRequirements.html‘, ‘original-specification.html‘, ‘requested-features.html‘, ‘requested-features.txt‘, ‘VFS.txt‘])````````````````````````````

遍历文件夹并删除特定格式文件的示例

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
def del_files(path):
    for root , dirs, files in os.walk(path):
        for name in files:
            if name.endswith(".tmp"):
                os.remove(os.path.join(root, name))
  print ("Delete File: " + os.path.join(root, name))
# test
if __name__ == "__main__":
    path = ‘/tmp‘
    del_files(path)

通过for循环即可完成目录的递归

#!/usr/bin/python
# -*- coding: gbk -*-

# os.walk()的使用
import os  

# 枚举dirPath目录下的所有文件  

def main():
#begin
    fileDir = "F:" + os.sep + "aaa"     # 查找F:\aaa 目录下
    for root, dirs, files in os.walk(fileDir):
    #begin
        for dir in dirs:
        #begin
            print(os.path.join(root, dir))
        #end
        for file in files:
        #begin
            print(os.path.join(root, file))
        #end
    #end
    os.system("pause")
#end  

if __name__ == ‘__main__‘:
#begin
    main()
#end  
时间: 2024-08-06 07:57:16

Python os.walk文件遍历的相关文章

Python os.walk() 方法遍历文件目录

概述 os.walk() 方法用于通过在目录树中游走输出在目录中的文件名,向上或者向下. os.walk() 方法是一个简单易用的文件.目录遍历器,可以帮助我们高效的处理文件.目录方面的事情. 在Unix,Windows中有效. 语法 walk()方法语法格式如下: os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]]) 参数 top -- 是你所要便利的目录的地址, 返回的是一个三元组(root,dirs,files)

Python OS简单文件/目录操作

Python OS简单文件/目录操作 Python的OS模块提供了丰富的文件和目录处理方法,这里指列举其中几个 参数不完全列举 删除.新建等操作 os.mkdir(path):在工作目录下创建一个名为path的文件夹 os.remove(path):删除路径为path的文件,如果不存在文件或者是一个文件夹则会抛出OSError os.rmdir(path):删除名为path的空文件夹,如果文件夹非空则会抛出OSError os.removedirs(path):递归删除文件夹 os.rename

python os.walk()遍历

os.walk()遍历 import os p='/bin' #设定一个路径 for i in os.walk(p): #返回一个元组 print (i[0]) #第一个元素是目录 print (i[1]) #第二个元素是文件夹 print (i[2]) #第三全元素是文件 返回一个元组,内有3个元素.第一个是路径.第二个是文件夹.第三个是文件

os.walk() 用于遍历目标文件路径的所有看见的看不见的文件和夹

import os def count_file_size(pathroot): print(pathroot) res = 0 for roots,dirs,files in os.walk(pathroot): for file in files: path = os.path.join(roots,file) print(path) res += os.path.getsize(path) return res path = os.path.dirname(__file__) print(

python os.walk()和os.path.walk()

一.os.walk() 函数声明:os.walk(top,topdown=True,onerror=None) (1)参数top表示需要遍历的顶级目录的路径. (2)参数topdown的默认值是“True”表示首先返回顶级目录下的文件,然后再遍历子目录中的文件.当topdown的值为"False"时,表示先遍历子目录中的文件,然后再返回顶级目录下的文件. (3)参数onerror默认值为"None",表示忽略文件遍历时的错误.如果不为空,则提供一个自定义函数提示错误

Linux Ubuntu 16.04 python os.walk

os.walk(top,topdown=True,onerror=None,followlinks=False) os.walk()是python中内置(built-in)的目录树生成(directory tree generator)函数. 对于每一个在top目录下的子目录(包括top目录本身),该函数都会生成一个包含三个元素的元组(tuple): (dirpath, dirnames, filenames).(string,list,list) dirpath是目录名称(string),di

Python os.walk() 方法

#coding=utf-8 import os #(dirpath, dirnames, filenames)[文件夹路径, 文件夹名字, 文件名] def file_name(file_dir): for root, dirs, files in os.walk(file_dir): for name in files: print(os.path.join(root,name)) for name in dirs: print(os.path.join(root, name)) #print

Python os.walk的用法与举例

os.walk(top, topdown=True, onerror=None, followlinks=False) 可以得到一个三元tupple(dirpath, dirnames, filenames), 第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件. dirpath 是一个string,代表目录的路径, dirnames 是一个list,包含了dirpath下所有子目录的名字. filenames 是一个list,包含了非目录文件的名字. 这些名字不包含路径信息

python os.walk

#coding utf-8 import os def main(): fileDir = 'F:'+os.sep+'aaa' for root,dirs,files in os.walk(fileDir): print (root) print (dirs) print (files) os.system('pause') if __name__=='__main__': main() >>> ================================ RESTART =====