python 文件操作,os.path.walk()的回调函数打印文件名

时间:2023-12-10 08:43:02

#coding=utf-8

import os
def find_file(arg,dirname,files):
    #for i in arg:
        #print i

for file in files:
        file_path=os.path.join(dirname,file)
        print 'file_path:',file_path
        if os.path.isfile(file_path) and (arg[0] in file or arg[1] in file):
            print 'file:%s\n'%file_path

os.path.walk(r'd:\\test2',find_file,('.txt','.png'))

c:\Python27\Scripts>python task_test.py
file_path: d:\\test2\file1
file_path: d:\\test2\file1.txt
file:d:\\test2\file1.txt

file_path: d:\\test2\file2
file_path: d:\\test2\file1\file2.txt
file:d:\\test2\file1\file2.txt

file_path: d:\\test2\file2\file3
file_path: d:\\test2\file2\file3.txt
file:d:\\test2\file2\file3.txt

file_path: d:\\test2\file2\file3\file4.txt
file:d:\\test2\file2\file3\file4.txt

进一步看每次循环dirname,file都是什么:

#coding=utf-8

import os
def find_file(arg,dirname,files):
    #for i in arg:
        #print i

for file in files:
        print "dirname: %s, file:%s" %(dirname,file)
        file_path=os.path.join(dirname,file)
        print 'file_path:',file_path
        if os.path.isfile(file_path) and (arg[0] in file or arg[1] in file):
            print 'file:%s\n'%file_path

os.path.walk(r'd:\\test2',find_file,('.txt','.png'))

c:\Python27\Scripts>python task_test.py
dirname: d:\\test2, file:file1
file_path: d:\\test2\file1
dirname: d:\\test2, file:file1.txt
file_path: d:\\test2\file1.txt
file:d:\\test2\file1.txt

dirname: d:\\test2, file:file2
file_path: d:\\test2\file2
dirname: d:\\test2\file1, file:file2.txt
file_path: d:\\test2\file1\file2.txt
file:d:\\test2\file1\file2.txt

dirname: d:\\test2\file2, file:file3
file_path: d:\\test2\file2\file3
dirname: d:\\test2\file2, file:file3.txt
file_path: d:\\test2\file2\file3.txt
file:d:\\test2\file2\file3.txt

dirname: d:\\test2\file2\file3, file:file4.txt
file_path: d:\\test2\file2\file3\file4.txt
file:d:\\test2\file2\file3\file4.txt

函数解释:

os.path.walk(top, func, arg)

回调函数(钩子),当一个事件发生时,自动调用指定函数

参数说明:

top:表示需要遍历的目录树的路径

func:表示回调函数,对遍历路径进行处理的函数。所谓回调函数,是作为某个函数的的参数使用,当某个时间触发时,程序将调用定义好的回调函数处理某个任务。该回调函数必须提供3个参数:第1个参数为walk()的参数arg,第2个参数表示目录列表dirname,第3个参数表示文件列表names。

arg:是传递给回调函数func的元组,为回调函数提供处理参数,回调函数的第一个参数就是用来接收这个传入的元组的,参数arg可以为空)

#coding=utf-8

import os

#回调函数

#coding=utf-8

import os

#回调函数

#调find_file函数时(1,2)传给arg,dirname和files是walk函数来传递的

def find_file(arg, dirname, files):

#for i in arg:

#    print i

for file in files:

file_path = os.path.join(dirname, file)

if os.path.isfile(file_path):

print "file:%s" %file_path

#调用

os.path.walk(r"d:\test2", find_file, (1,2))