实现遍历:
#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()

python遍历的更多相关文章

  1. 用Python遍历目录

    用Python遍历指定目录下的文件,一般有两种常用方法,但它们都是基于Python的os模块.下面两种方法基于Python2.7,主要用到的函数如下: 1.os.listdir(path):列出目录下 ...

  2. python 遍历文件夹 文件

    python 遍历文件夹 文件   import os import os.path rootdir = "d:\data" # 指明被遍历的文件夹 for parent,dirn ...

  3. python遍历目录文件脚本的示例

    例子 自己写的一个Python遍历文件脚本,对查到的文件进行特定的处理.没啥技术含量,但是也记录一下吧. 代码如下 复制代码 #!/usr/bin/python# -*- coding: utf-8 ...

  4. python遍历一个目录,输出所有文件名

    python遍历一个目录,输出所有文件名 python os模块 os import os  def GetFileList(dir, fileList):  newDir = dir  if os. ...

  5. Python遍历List集合四种方法

    这篇文章主要介绍了Python 列表(List) 的四种遍历方法实例 详解的相关资料,需要的朋友可以参考下 分别是:直接遍历对象 通过索引遍历 通过enumerate方法 通过iter方法. 使用Py ...

  6. [python]python 遍历一个list 的小例子:

    [python]python 遍历一个list 的小例子: mlist=["aaa","bbb","ccc"]for ss in enume ...

  7. python 遍历list并删除部分元素

    python 遍历list并删除部分元素https://blog.csdn.net/afgasdg/article/details/82844403有两个list,list_1 为0-9,list_2 ...

  8. Python遍历文件夹

    许多次需要用python来遍历目录下文件, 这一次就整理了记录在这里. 随实际工作,不定期更新. import os class FileTraversal: def __init__(self, r ...

  9. 【python】Python遍历dict的key最高效的方法是什么?

    来源:https://segmentfault.com/q/1010000002581747 方法一:直接遍历 速度快 for key in _dict: pass 方法二:iterkeys() 速度 ...

  10. python遍历文件夹下的文件

    在读文件的时候往往需要遍历文件夹,python的os.path包含了很多文件.文件夹操作的方法.下面列出: os.path.abspath(path) #返回绝对路径 os.path.basename ...

随机推荐

  1. 【Linux常见命令】ip命令

    ip命令是用来配置网卡ip信息的命令,且是未来的趋势,重启网卡后IP失效. ip - show / manipulate routing, devices, policy routing and tu ...

  2. 开发AI+诊疗生发系统,「先锋汇美」借力人工智能辅助诊疗实现头皮医学检测...

    困扰年轻人的脱发问题萌生了新兴的产业链.36氪先前曾剖析过近来火热的植发市场,更多人则选择"防范于未然","头皮检测"服务备受关注.此前,人们对"头皮 ...

  3. 关于Python的JSON

    1.json模块load/loads.dump/dumps区别:(摘自这里) 实际上json就是python字典的字符串表示,但是字典作为一个复杂对象是无法直接转换成定义它的代码的字符串,python ...

  4. 快放弃你的管家软件吧! Part 2 强制删除

    在Windows系统中,难免会遇到用常规方法无法删除文件的情况. 经常有遇到过一些情况? 软件卸载了,有些文件夹就是删不掉,提示被占用,mmp,这时候你肯定想到了360文件粉碎机! mmp,我就删个文 ...

  5. 第K短路+严格第K短路

    所谓K短路,就是从s到t的第K短的路,第1短就是最短路. 如何求第K短呢?有一种简单的方法是广度优先搜索,记录t出队列的次数,当t第k次出队列时,就是第k短路了.但点数过大时,入队列的节点过多,时间和 ...

  6. Nmon 监控结果分析

    一:CPU信息 SYS_SUMM图表: 1.折线图中蓝线为cpu占有率变化情况:粉线为磁盘IO的变化情况: 2.下面表各种左边的位磁盘的总体数据,包括如下几个: Avg tps during an i ...

  7. 如何用Hexo搭建个人博客

    以前用Wordpress搭建过一个博客网站,Wordpress虽然安装简单,功能强大,但是对于个人建站来说有点复杂了.最近发现用Hexo建站很流行,于是将网站从Wordpress迁移到了Hexo. H ...

  8. golang之array

    golang使用array表示固定大小的数组,使用slice表示动态数组. package main import "fmt" func main() { var a = [5]i ...

  9. Shell简单实现多线程

        一.目的 解决Shell脚本单线程下效率低下的问题 二.适用场景 需要在Linux系统执行同一项命令,但是针对不同的对象,例如PING检测主机,当然可以延展,只要是命令之间不会产生冲突就可以了 ...

  10. 【Spark】这一篇或许能让你大概了解如何通过JavaAPI实现DataFrame的相关操作

    文章目录 需求概述 步骤 一.创建Maven工程并导包 二.选用第一种方法:利用反射机制配合样例类构建DataFrame 开发代码 选用第二种方法:通过StrucType配合Row构建DataFram ...