linux运维-python递归遍历目录+案例应用

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

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

os.walk(top[, topdown=True[, onerror=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 os
filedir = "/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 os

def 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 os

def 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 os
import shutil

def 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、案例场景

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

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

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

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

# -*- coding:utf-8 -*-
#读取excel数据,存入list。

import xlrd

path_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_list

my_List = read_excel_to_list(path_file)

if "57939176" in my_List:
    print("ok")
else:
    print('false')

#print(my_List)

3、案例需求实现代码

#案例需求:把voice目录及其下各个子目录的 指定分机号码 文件夹,拷贝到指定目录。
#

import os
import shutil
import xlrd

path_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_list

my_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:
            source_Dir = os.path.join(root,dir_list)            #生成目录的全路径
            shutil.copytree(source_Dir,path_dest+dir_list)      #使用shutil.copytree方法复制整个目录
            #os.system("cp -r "+source_Dir+" "+path_dest)       #使用os.system方法执行shell命令
            #print(source_Dir)
        else:
            continue
print("job is done")

猜你喜欢

转载自www.cnblogs.com/he-ding/p/10045246.html