1. 程式人生 > >linux運維-python遞迴遍歷目錄+案例應用

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")