当前位置: 首页 > news >正文

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

 

转载于:https://www.cnblogs.com/yaner2018/p/9550412.html

相关文章:

  • C#基础总结 .
  • LeetCode 15. 3Sum; 16. 3Sum Closest; 259. 3Sum Smaller; 18. 4Sum
  • 蓝牙4.0 For IOS
  • gpio_direction_output和gpio_set_value
  • JVM系列三:JVM运行时数据区
  • web安全Wargame—Natas解题思路(1-26)
  • jQuery插件开发详细教程
  • Vue.js从Virtual DOM映射到真实DOM的过程
  • screen终端命令使用
  • 德国精品软件   cFosSpeed 网络优化软件
  • 数据分析师完整的知识结构
  • 结构体中定义函数指针
  • 人工智能与勒索病毒较量,你猜最后谁能赢了?
  • 行为型设计模式之命令模式(Command)
  • WPF DataGrid 每行ComboBox 内容不同的设置方法
  • 【笔记】你不知道的JS读书笔记——Promise
  • C++类的相互关联
  • CentOS从零开始部署Nodejs项目
  • ERLANG 网工修炼笔记 ---- UDP
  • Java新版本的开发已正式进入轨道,版本号18.3
  • JS创建对象模式及其对象原型链探究(一):Object模式
  • Js基础知识(四) - js运行原理与机制
  • js中forEach回调同异步问题
  • Laravel 菜鸟晋级之路
  • Markdown 语法简单说明
  • mysql innodb 索引使用指南
  • Mysql5.6主从复制
  • Stream流与Lambda表达式(三) 静态工厂类Collectors
  • 关于springcloud Gateway中的限流
  • 规范化安全开发 KOA 手脚架
  • 七牛云假注销小指南
  • 腾讯视频格式如何转换成mp4 将下载的qlv文件转换成mp4的方法
  • 责任链模式的两种实现
  • 06-01 点餐小程序前台界面搭建
  • Spark2.4.0源码分析之WorldCount 默认shuffling并行度为200(九) ...
  • 阿里云ACE认证之理解CDN技术
  • 关于Kubernetes Dashboard漏洞CVE-2018-18264的修复公告
  • 专访Pony.ai 楼天城:自动驾驶已经走过了“从0到1”,“规模”是行业的分水岭| 自动驾驶这十年 ...
  • #免费 苹果M系芯片Macbook电脑MacOS使用Bash脚本写入(读写)NTFS硬盘教程
  • #使用清华镜像源 安装/更新 指定版本tensorflow
  • $NOIp2018$劝退记
  • (1)(1.8) MSP(MultiWii 串行协议)(4.1 版)
  • (2020)Java后端开发----(面试题和笔试题)
  • (cos^2 X)的定积分,求积分 ∫sin^2(x) dx
  • (day 12)JavaScript学习笔记(数组3)
  • (iPhone/iPad开发)在UIWebView中自定义菜单栏
  • (k8s中)docker netty OOM问题记录
  • (TipsTricks)用客户端模板精简JavaScript代码
  • (二)什么是Vite——Vite 和 Webpack 区别(冷启动)
  • (附源码)spring boot公选课在线选课系统 毕业设计 142011
  • (实战篇)如何缓存数据
  • (一)基于IDEA的JAVA基础10
  • (已解决)什么是vue导航守卫
  • .gitignore
  • .gitignore文件设置了忽略但不生效