博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
linux运维-python递归遍历目录+案例应用
阅读量:4646 次
发布时间:2019-06-09

本文共 5794 字,大约阅读时间需要 19 分钟。

一、python中walk()方法遍历目录基本使用

1、walk()方法的基本语法

os.walk(top[, topdown=True[, οnerrοr=None[, followlinks=False]]])

  • top -- 是你所要遍历的目录的地址.
  • topdown -- 可选,为 True,则优先遍历top目录,否则优先遍历 top 的子目录(默认为开启)。
  • onerror -- 可选,需要一个 callable 对象,当 walk 需要异常时,会调用。
  • followlinks -- 可选,如果为 True,则会遍历目录下的快捷方式,默认开启
  • return None-- 该函数没有返回值会使用yield关键字抛出一个存放当前该层目录(root,dirs,files)的三元组,最终将所有目录层的的结果变为一个生成器

          root 所指的是当前正在遍历的这个文件夹的本身的地址

          dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录)

          files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)

2、基本使用举例

2.1walk()基本使用,输出基础遍历的各个结果及形式。

#!/usr/bin/ python# walk()基本使用,输出基础遍历的各个结果及形式。import osfiledir = "/home/dsh/walk_test/"def walk_1():        filedir = "/home/dsh/walk_test/"    for root,dirs,files in os.walk(filedir):        print(root)        print(dirs)        print(files)        print('***************************')    #os.system('pause')walk_1()

2.2.walk()基本使用,循环输出各级目录名称。

#!/usr/bin/ python#walk()基本使用,循环输出各级目录名称。import osdef walk_test():    filedir = "/home/dsh/wall_test/"    for root,dirs,files in os.walk(filedir):        for dirs_list in dirs:            print(dirs_list)            print('************')        #print("###############")walk_test()

2.3walk()基本使用,循环输出各级目录下的文件名称

#!/usr/bin/ python# walk()基本使用,输出各级目录下的文件的名称。import osdef walk_test():    filedir = "/home/dsh/wall_test/"    for root,dirs,files in os.walk(filedir):        for files_list in files:            print(files_list)            print("##########")walk_test()

2.4 walk()基本使用,循环输出各级目录,及目录下的文件名称(带有全路径)

#!/usr/bin/ python# walk()基本使用,输出各级目录,及目录下的文件的名称(带有路径)。import osimport shutildef walk_test():    filedir = "/home/dsh/wall_test/"    for root,dirs,files in os.walk(filedir):        for dir_list in dirs:            print(os.path.join(root,dir_list))        for files_list in files:            print(os.path.join(root,files_list))        print("##########")walk_test()

二、应用案例1

1、案例场景

需求:复制 指定分机号码目录  到  指定文件夹

如下图,分机号码语音文件目录存储结构如下:

2、需要知识点(python读取excel数据,存入list)

根据需求,需要把指定的分机号码数据,存入的list中,以便用来比对是否是目标数据

# -*- coding:utf-8 -*-#读取excel数据,存入list。import xlrdpath_file = "/home/dsh/wall_test/src/123.xlsx"def read_excel_to_list(path_to_file):    my_list = []    file_name = path_to_file  #关联带读取的excel文件,最好使用全路径    book_read = xlrd.open_workbook(file_name)   #打开文件,创建book对象    sheet1_read = book_read.sheet_by_index(0)   #使用book对象,获取工作簿对象    nrows_read = sheet1_read.nrows                      #获取sheet1工作簿的总行数    #ncols_read = sheet1_read.ncols                     #获取sheet1工作薄中的总列数    #print (nrows_read)    for i in range(nrows_read):        cell_value = sheet1_read.cell_value(i,0)        cell_str = str(cell_value).split('.')[0]        #print(cell_str,end='\n')        my_list.append(cell_str)    return my_listmy_List = read_excel_to_list(path_file)if "57939176" in my_List:    print("ok")else:    print('false')#print(my_List)

 

3、案例需求实现代码

#案例需求:把voice目录及其下各个子目录的 指定目录(号码)下的文件,拷贝到其他指定目录。#import osimport shutilimport xlrdpath_file = "/home/dsh/wall_test/src/123.xlsx"path_source = "/var/spool/voice/voice/"#path_source = "/home/dsh/walk_test/"path_dest = "/var/spool/voice/2018/"def read_excel_to_list(path_to_file):    my_list = []    file_name = path_to_file  #关联带读取的excel文件,最好使用全路径    book_read = xlrd.open_workbook(file_name)   #打开文件,创建book对象    sheet1_read = book_read.sheet_by_index(0)   #使用book对象,获取工作簿对象    nrows_read = sheet1_read.nrows                      #获取sheet1工作簿的总行数    #ncols_read = sheet1_read.ncols                     #获取sheet1工作薄中的总列数    #print (nrows_read)    for i in range(nrows_read):        cell_value = sheet1_read.cell_value(i,0)        cell_str = str(cell_value).split('.')[0]        #print(cell_str,end='\n')        my_list.append(cell_str)    return my_listmy_List = read_excel_to_list(path_file)for root,dirs,files in os.walk(path_source):                    #关联待遍历的指定目录    for dir_list in dirs:                                       #遍历目录集合        if dir_list in my_List:            os.system("mkdir -p "+path_dest+dir_list)            source_Dir = os.path.join(root,dir_list)            #生成目标目录的全路径            #shutil.copytree(source_Dir,path_dest+dir_list)     #使用shutil.copytree方法复制整个目录            os.system("cp "+source_Dir+"/* "+path_dest+dir_list)         #使用os.system方法执行shell命令            #print(source_Dir)        else:            continue        print("job is done")

三、应用案例2

需求描述:遍历指定目录,把其及其子目录下所有文件,移动到指定文件内。

代码实现:

#案例需求:把2019目录及其下各个子目录下的所有文件(仅文件),拷贝到指定目录2018中。#import osimport shutilimport xlrdpath_file = "/home/dsh/wall_test/src/123.xlsx"path_source = "/var/spool/voice/2019/"#path_source = "/home/dsh/walk_test/"path_dest = "/var/spool/voice/2018/"'''def read_excel_to_list(path_to_file):    my_list = []    file_name = path_to_file  #关联带读取的excel文件,最好使用全路径    book_read = xlrd.open_workbook(file_name)   #打开文件,创建book对象    sheet1_read = book_read.sheet_by_index(0)   #使用book对象,获取工作簿对象    nrows_read = sheet1_read.nrows                      #获取sheet1工作簿的总行数    #ncols_read = sheet1_read.ncols                     #获取sheet1工作薄中的总列数    #print (nrows_read)    for i in range(nrows_read):        cell_value = sheet1_read.cell_value(i,0)        cell_str = str(cell_value).split('.')[0]        #print(cell_str,end='\n')        my_list.append(cell_str)    return my_listmy_List = read_excel_to_list(path_file)'''for root,dirs,files in os.walk(path_source):                    #关联待遍历的指定目录    for file_list in files:                                     #遍历文件集合        #os.system("mkdir -p "+path_dest+dir_list)        source_filedir = os.path.join(root,file_list)           #生成目标文件的全路径        shutil.move(source_filedir,path_dest)                   #使用shutil.move方法移动文件到指定目录        #os.system("cp "+source_Dir+"/* "+path_dest)            #使用os.system方法执行shell命令        #print(source_Dir)        print("job is done")

 

转载于:https://www.cnblogs.com/he-ding/p/10045246.html

你可能感兴趣的文章
Python20-Day05
查看>>
Real World Haskell 第七章 I/O
查看>>
C#操作OFFICE一(EXCEL)
查看>>
【js操作url参数】获取指定url参数值、取指定url参数并转为json对象
查看>>
ABAP 程序间的调用
查看>>
移动端单屏解决方案
查看>>
web渗透测试基本步骤
查看>>
使用Struts2标签遍历集合
查看>>
angular.isUndefined()
查看>>
第一次软件工程作业(改进版)
查看>>
网络流24题-飞行员配对方案问题
查看>>
Jenkins 2.16.3默认没有Launch agent via Java Web Start,如何配置使用
查看>>
引入css的四种方式
查看>>
iOS开发UI篇—transframe属性(形变)
查看>>
3月7日 ArrayList集合
查看>>
jsp 环境配置记录
查看>>
Python03
查看>>
LOJ 2537 「PKUWC2018」Minimax
查看>>
使用java中replaceAll方法替换字符串中的反斜杠
查看>>
Some configure
查看>>