python遍历

实现遍历:

#coding=utf-8
#遍历的2种方式

import os

#1.使用os.listdir(f)

def traverse(f):
    fs = os.listdir(f)
    for f1 in fs:
        tmp_path = os.path.join(f,f1)
        if not os.path.isdir(tmp_path):
            print('文件: %s'%tmp_path)
        else:
            print('文件夹:%s'%tmp_path)
            traverse(tmp_path)
            
path = 'F:/source_files/python/'
traverse(path)

#2.使用os.walk
path = 'F:/source_files/python/'
 
for fpathe,dirs,fs in os.walk(path):
    for f in fs:
        print(os.path.join(fpathe,f))

案例1:

#coding=utf-8
'''
Created on 2018年8月28日

@author: yanerfree

获取某一目录下所有的sql文件
'''
import os
import shutil 

def traverse(file_path,save_fath):
    list = os.listdir(file_path)
    for i in range(0,len(list)):
        #print list[i]
        tmp_path = os.path.join(file_path,list[i])
        #print tmp_path
        if os.path.isfile(tmp_path):
            if str(list[i])[-3:] == "sql":
                #复制改文件到指定目录下
                #print "sql文件",list[i]
                save_as = os.path.join(save_fath,str(list[i])) 
                #print save_as
                shutil.copyfile(tmp_path, save_as)
                
        else:
            traverse(tmp_path,save_fath)
             
if __name__ == '__main__':
    starttime=datetime.datetime.now().microsecond
    
    file_path = r'./DCKeyMgrSystemExts'
    save_fath = r'./sql'
    traverse(file_path, save_fath)
    
    endtime=datetime.datetime.now().microsecond
    costtime=endtime-starttime
    print "totally cost %d ms"%costtime

案例2:

#coding=utf-8
'''
Created on 2018年8月28日

@author:yanerfree

get the version number of the file (.dll)  in bulk
批量获取dll文件的版本号

'''
import os
import sys
import win32api
import xlwt
from xlwt import *


class GetFileVersionNo():
    
    def __init__(self,file_path,save_path):
        #初始化
        self.file_path = file_path
        self.save_path = save_path
            
    def traverse_dir(self,file_path):
        #traverse the directory of file_path(the file are .dll)
        myList=[]#save result
        list = os.listdir(file_path)
        for i in range(0,len(list)):
            print list[i]
            tmp_path = os.path.join(file_path,list[i])
            print tmp_path
            if os.path.isfile(tmp_path):
                #if str(list[i]).split(".")[1] =="dll":
                if str(list[i])[-3:] == "dll":
                    #judge if the filename ended with  ".dll"
                    #print tmp_path,getFileVersion(tmp_path)
                    myList.append((list[i],self.getFileVersion(tmp_path)))
                
        return myList
    
    def getFileVersion(self,file_name):
        #get the version of file
        info = win32api.GetFileVersionInfo(file_name, os.sep)
        ms = info['FileVersionMS']
        ls = info['FileVersionLS']
        version = '%d.%d.%d.%04d' % (win32api.HIWORD(ms), win32api.LOWORD(ms), win32api.HIWORD(ls), win32api.LOWORD(ls))
        print version
        return version
    

    def writeToExcel(self):
        file_path = self.file_path
        save_path = self.save_path
        #write to excel
        print "create a workbook"
        book = Workbook(encoding='utf-8')#create a workbook
        sheet = book.add_sheet('Sheet1')#create a sheet
        #set style
        font = xlwt.Font() # 字体
        font.name = 'Times New Roman'
        font.bold = True
        font.underline = False
        font.italic = False
        style = xlwt.XFStyle() # 创建一个格式
        style.font = font # 设置格式字体
        
        #sheet.write(0, 0, label = 'Formatted value', style) # Apply the Style to the Cell
        sheet.write(0, 0, "no",style)
        sheet.write(0, 1, "file_name",style)
        sheet.write(0, 2, "file_version",style)
    
        list = self.traverse_dir(file_path)
        row=0
        num=0
        for item in list:
            row += 1
            num += 1
            sheet.write(row, 0, num, style)
            sheet.write(row, 1,item[0] , style)
            sheet.write(row, 2,item[1] , style)
            
        book.save(save_path)

if __name__ == '__main__':
    #1)获取指定目录下dll文件的版本号
    file_path1 = r'../01_dev/Exts'
    save_path1 = r'../04_result/result_dev.xls'
    getVersion1 = GetFileVersionNo(file_path1,save_path1)
    getVersion1.writeToExcel()